c++怎樣讓返回對象的函數不調用拷貝建構函式

來源:互聯網
上載者:User

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請按任意鍵繼續. . .*/

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.