C++程式設計方法3:移動建構函式

來源:互聯網
上載者:User

標籤:led   ace   cal   turn   記憶體   return   clu   ide   ++   

移動拷貝建構函式

文法:

ClassName(ClassName&&);

目的:

用來偷“臨時變數”中的資源(比如記憶體)

臨時變數被編譯器設定為常量形式,使用拷貝建構函式無法將資源偷出來(“偷”是對原來對象的一種改動,違反常量的限制)

基於“右值引用“定義的移動建構函式支援接受臨時變數,能偷出臨時變數中的資源;

 

#include <iostream>using namespace std;class Test{public:    int *buf;//only for demo    Test()    {        buf = new int(3);        cout << "Test():this->[email protected] " << hex << buf << endl;    }    ~Test()    {        cout << "~Test(): this->[email protected]" << hex << buf << endl;        if (buf)            delete buf;    }    Test(const Test& t) :buf(new int(*t.buf))    {        cout << "Test(const Test&) called.this->[email protected]" << hex << buf << endl;    }    Test(Test&& t) :buf(t.buf)    {        cout << "Test(Test&&) called.this->[email protected]" << hex << buf << endl;        t.buf = nullptr;    }};Test GetTemp(){    Test tmp;    cout << "GetTemp(): [email protected]" << hex << tmp.buf << endl;    return tmp;//返回給未知名字的對象}void fun(Test t){    cout << "fun(Test t):[email protected] " << hex << t.buf << endl;}int main(){    Test a = GetTemp();    cout << "main():[email protected]" << hex << a.buf << endl;    fun(a);//拷貝調用    return 0;}

 

//備忘:編譯器對傳回值做了最佳化,因此增加編譯選項,禁止編譯器進行傳回值的最佳化
/*
g++ wo2.cpp --std=c++11 -fno-elide-constructors
*/

 

C++程式設計方法3:移動建構函式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.