码迷,mamicode.com
首页 > 其他好文 > 详细

复制构造函数和析构函数经典例子

时间:2015-04-16 10:18:30      阅读:125      评论:0      收藏:0      [点我收藏+]

标签:c++   面试题   对象   计算机   指针   

#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预留的空间,所以减少了返回临时对象的生成


复制构造函数和析构函数经典例子

标签:c++   面试题   对象   计算机   指针   

原文地址:http://blog.csdn.net/u014082714/article/details/45071057

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!