拷贝构造函数的调用

孤街醉人 提交于 2019-12-27 16:30:33

参考如下文章:
拷贝构造函数什么时候调用?
补充:
当一个函数中形参和返回值都是对象,理论上应该调用两次拷贝构造函数,但是实际上只调用了一次。编译器为了提高效率把这两次合并了。
如:

#include<iostream>
#include<string>
#include<vector>
using namespace std;
class B{
private:
	int data;
public:
	B(){
		cout << "default constructor" << endl;
	}
	B(const B &other){
		cout << "kaobei" << endl;
	}
	~B(){
		cout << "destructed" << endl;
	}
	B(int i) :data(i){
		cout << "constructed by parameter" << data << endl;
	}
};
B Play(B b){//函数中形参和返回值都是对象
	return b;
}
int main(){
	B temp = Play(5);
	return 0;	
}
//输出结果:
constructed by parameter5
kaobei
destructed
destructed
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!