我们知道拷贝构造函数有两种“默默”的方式被调用
1. 想函数传入 值参数
2. 函数返回 值类型
今天我们讨论函数返回值类型的情况。
得到结论是
1. 当对象有拷贝构造函数(系统为我们生成、或者我们自己写拷贝构造函数)可以被隐式调用时,函数返回时会使用拷贝构造函数。
2. 当对象的拷贝构造函数声明成为explicit(不能被隐式调用时),函数返回时会使用move构造函数。
先看开始的代码。
#include <iostream>#include <memory>using namespace std;class Thing{public:	int		member_;	Thing():member_(0){  //默认构造函数	}	Thing(Thing& other):member_(other.member_){//拷贝构造函数			cout << "copy" << endl;	}		Thing(Thing&& other):member_(other.member_){//move构造函数		cout << "move" << endl;	}};Thing getThingByReturnValue(){	Thing thing;	thing.member_ = 1;	cout << "in method /t" <<  &thing.member_ << endl;	return thing;//会调用到拷贝构造函数}unique_ptr<int> getBySmartPtr(){	unique_ptr<int> p(new int);	cout << "in method /t" << *p << endl;//注意unique_ptr已经重载了*操作符,实际输出的是裸指针的内存地址	return p;//会调用unique_ptr move构造函数}void main(){	Thing th  = getThingByReturnValue();	cout << "out method /t" << &th.member_ << endl;	auto p = getBySmartPtr();	cout << "out method /t" << *p << endl;//注意unique_ptr已经重载了*操作符,实际输出的是裸指针的内存地址}/*in method       003CF798copyout method      003CF88C  //可见getThingByReturnValue调用的是Thing的copy构造函数in method       -842150451out method      -842150451  //可见getBySmartPtr调用的是unique_ptr的move构造函数请按任意键继续. . .*/为什么我们写的类会调用copy,而unique_ptr会调用move??百思不得其解。。睡觉时想到了,explicit修饰构造函数的用法。给拷贝构造函数加上explicit试试。
explicit Thing(Thing& other):member_(other.member_){//拷贝构造函数	cout << "copy" << endl;}/*in method       003EFC18moveout method      003EFD0Cin method       -842150451out method      -842150451请按任意键继续. . .*/