#include<iostream>
using namespace std;
class A
{
public:
A()
{
cout<<"this is construction"<<endl;
}
virtual ~A()
{
cout<<"this is destruction"<<endl;
}
};
A fun()
{
A a;
return a;
}
int main()
{
{
A a;
a=fun();
}
return 0;
}
运行结果:
this is Construction
this is Construction
this is destruction
this is destruction
this is destruction
结果析构比构造多一个,这是因为fun函数返回时生成了一个临时对象,这个临时对象是默认复制构造函数调用的(因为上面代码本身没有定义赋值构造函数,所以调用系统默认的)。然后调用赋值函数(也是默认的)赋值给主函数的对象a。
#include<iostream>
using namespace std;
class A
{
public:
A()
{
cout<<"this is construction"<<endl;
}
virtual ~A()
{
cout<<"this is destruction"<<endl;
}
};
A fun()
{
A a;
return a;
}
int main()
{
{
A a=fun();
}
return 0;
}
运行结果:this is Construction
this is destruction
this is destruction
下面加上自定义的赋值构造函数和赋值函数#include<iostream>
using namespace std;
class A
{
public:
A()
{
cout<<"this is construction"<<endl;
}
virtual ~A()
{
cout<<"this is destruction"<<endl;
}
A (A&a)
{
cout<<"this is Copy Construction"<<endl;
}
A&operator=(const A&a)
{
cout<<"this is assignment"<<endl;
return *this;
}
};
A fun()
{
A a;
return a;
}
int main()
{
{
A a;
a=fun();
}
return 0;
}
运行结果为:
this is Construction
this is Construction
this is Copy Construction
this is destruction
this is assignment
this is destruction
this is destruction
代码:#include<iostream>
using namespace std;
class A
{
public:
A()
{
cout<<"this is construction"<<endl;
}
virtual ~A()
{
cout<<"this is destruction"<<endl;
}
A (A&a)
{
cout<<"this is Copy Construction"<<endl;
}
A&operator=(const A&a)
{
cout<<"this is assignment"<<endl;
return *this;
}
};
A fun()
{
A a;
return a;
}
int main()
{
{
// A a;
//a=fun();
A a=fun();
}
return 0;
}
运行结果:this is Construction
this is Copy Construction
this is destruction
this is destruction返回对象直接使用为a预留的空间,所以减少了返回临时对象的生成