拷贝构造与赋值构造函数的区别:http://blog.csdn.net/sinhua_ren/article/details/1704884
classA a;
classA b=a; 拷贝构造;相当于classA b(a) ,在声明的时候其实b还没有分配内存,所以b要构造
b=a;赋值构造--因为b已经有了,只是按照a来修改b中的内容而已
#include
using namespace std;
static int static_index = 0;
class ParentA
{
public:
ParentA(int a):index(a)
{
cout << "construct A " <
<< endl;
}
ParentA(const ParentA &pa)
{
index = ++static_index;
cout << "copy construct A " << index << endl;
}
ParentA &operator=(const ParentA &pa)
{
index = ++static_index;
cout << "= construct A " << index << endl;
return *this;
}
~ParentA()
{
cout << "unconstruct A " << index << endl;
}
int index;
};
ParentA func(ParentA pa) {
ParentA a(++static_index);
return a;//先 拷贝构造新a,后析构旧a,析构pa,
}
void main(char **argv, int arg)
{
ParentA pa(++static_index);
func(pa);
ParentA tmp2(++static_index);
return;
}
结果:
construct A 1
copy construct A 2
construct A 3
copy construct A 4
unconstruct A 3
unconstruct A 2
unconstruct A 4 // 应为函数func(pa) 返回后没有用了,就里面析构了,在tmp2 (index=5)前面就析构了
construct A 5
unconstruct A 5
unconstruct A 1
如果 39行改为:ParentA tmp1=func(pa);
结果:
construct A 1
copy construct A 2
construct A 3
copy construct A 4
unconstruct A 3
unconstruct A 2
construct A 5
unconstruct A 5
unconstruct A 4 // 应为函数ParentA tmp1=func(pa) ; tmp1接收了,所以析构在tmp2(index=5)后面才析构
unconstruct A 1
如果
void main(char **argv, int arg)
{
ParentA pa(++static_index);
ParentA tmp1=func(pa); // 这行与下一行 func(pa); 结果完全一样 ,tmp1 的index=4
// func(pa); // index=4;
return;
}
结果:
construct A 1
copy construct A 2
construct A 3
copy construct A 4
unconstruct A 3
unconstruct A 2
unconstruct A 4
unconstruct A 1