c++怎樣讓返回對象的函數不調用拷貝建構函式
我們知道拷貝建構函式有兩種“默默”的方式被調用
1. 想函數傳入 值參數
2. 函數返回 實值型別
今天我們討論函數傳回值類型的情況。
得到結論是
1. 當對象有拷貝建構函式(系統為我們產生、或者我們自己寫拷貝建構函式)可以被隱式調用時,函數返回時會使用拷貝建構函式。
2. 當對象的拷貝建構函式聲明成為explicit(不能被隱式調用時),函數返回時會使用move建構函式。
先看開始的代碼。
#include <iostream>#include <memory>using namespace std;class Thing{public:intmember_;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請按任意鍵繼續. . .*/