標籤: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:移動建構函式