拷贝构造函数在哪些地方用,函数参数,函数返回值

首先看个程序。

#include <iostream>
using namespace std;

class A
{
public:
	A()
	{
		cout << "A"<<endl;
	}
	~A()
	{
		cout << "~A"<<endl;
	}
private:
	int x;

};

void main()
{
	A a;
	A b(a);
	A c(a);
}


输出结果是:

A
~A
~A
~A
请按任意键继续. . .

 

=================================================

关于函数参数和函数返回值的构造问题。

函数参数和返回值的构造都是调用的拷贝构造函数。

并且在函数返回时都需要析构。

 

#include <iostream>
using namespace std;

class A
{
public:
	A()
	{
		cout << "A" <<endl;
	}
	~A()
	{
		cout << "~A" <<endl;
	}
private:
	string x,y;
};

class B : public A
{
public:
	B()
	{
		cout << "B" <<endl;
	}
	~B()
	{
		cout << "~B" <<endl;
	}
private:
	string x1,y1;
};

B fun(B b)
{
	return b;
}

void main()
{
	B a,b;
	b = fun(a);
}

输出结果:

A
B
A
B
~B
~A
~B
~A
~B
~A
~B
~A
请按任意键继续. . .

当把函数调用注释掉后,输出结果是:

A
B
A
B
~B
~A
~B
~A
请按任意键继续. . .

 

可见相比fun函数的调用,只是多了两次析构函数的调用而已。

 

#include <iostream>
using namespace std;

class A
{
public:
	A()
	{
		cout << "A" <<endl;
	}
	A(const A &a)
	{
		cout << "construct A" <<endl;
	}
	~A()
	{
		cout << "~A" <<endl;
	}
private:
	string x,y;
};

class B : public A
{
public:
	B()
	{
		cout << "B" <<endl;
	}
	B(const B &a)
	{
		cout << "construct B" <<endl;
	}
	~B()
	{
		cout << "~B" <<endl;
	}
private:
	string x1,y1;
};

B fun(B b)
{
	return b;
}

void main()
{
	B a,b;
	b = fun(a);
}


PS:调用拷贝构造函数之前会自动调用父类的构造函数

 A
B
A
B
A
construct B
A
construct B
~B
~A
~B
~A
~B
~A
~B
~A
请按任意键继续. . .

 

//多余调用的两次析构函数。是函数参数和返回值的析构。

//而函数参数和返回值都是拷贝构造函数完成构造的。

//参考文献:

//http://www.cnblogs.com/renyuan/archive/2012/12/29/2839230.html

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值