我們知道拷貝構造函數有兩種“默默”的方式被調用
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 003CF798
copy
out method 003CF88C //可見getThingByReturnValue調用的是Thing的copy構造函數
in method -842150451
out method -842150451 //可見getBySmartPtr調用的是unique_ptr的move構造函數
請按任意鍵繼續. . .
*/
為什麼我們寫的類會調用copy,而unique_ptr會調用move??百思不得其解。。睡覺時想到了,explicit修飾構造函數的用法。給拷貝構造函數加上explicit試試。
explicit Thing(Thing& other):member_(other.member_){//拷貝構造函數
cout << "copy" << endl;
}
/*
in method 003EFC18
move
out method 003EFD0C
in method -842150451
out method -842150451
請按任意鍵繼續. . .
*/