c++ 11 移动语义
生活随笔
收集整理的這篇文章主要介紹了
c++ 11 移动语义
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
C++?已經擁有了拷貝構造函數,?和賦值函數,它們主要定位為淺和深度拷貝,?新增加一個移動構造函數,主要避免拷貝構造。
在定義了移動構造函數的情況下,在實參(argument)是一個右值(rvalue,包括xvalue和prvalue)的情況下會調用移動構造函數,而不是調用復制構造函數?
可以使用std::move語句可以將左值變為右值而避免拷貝構造,修改代碼如下:
編譯器會對返回值進行優化,簡稱RVO,是編譯器的一項優化技術,它涉及(功能是)消除為保存函數返回值而創建的臨時對象。
-fno-elide-constructors,此選項作用是,在 g++ 上編譯時關閉 RVO。
shell> g++ main.cpp -std=c++11?-fno-elide-constructors
#include <iostream> using namespace std;class Test { public:Test(int a = 0){d = new int(a);cout << "cs" << this <<endl;}Test(const Test & tmp){d = new int;*d = *(tmp.d);cout << "copy\n";}// Test(Test && tmp) // { // 移動構造函數 // d = tmp.d; // tmp.d = NULL; // 將臨時值的指針成員置空 // cout << "mv" << this << endl; // }~Test(){if(d != NULL){delete d;cout << "delete d\n";}cout << "ds: " << this << endl;}int * d; };Test GetTmp() {Test h;cout << "Resource from " << __func__ << ": " << (void *)h.d << endl;return h; }int main() {//Test&& obj = GetTmp();Test obj = GetTmp();cout << "Resource from " << __func__ << ": " << (void *)obj.d << endl;return 0; }
?
?
?
使用移動語義后
#include <iostream> using namespace std;class Test { public:Test(int a = 0){d = new int(a);cout << "cs" << this <<endl;}Test(const Test & tmp){d = new int;*d = *(tmp.d);cout << "copy\n";}Test(Test && tmp){ // 移動構造函數d = tmp.d;tmp.d = NULL; // 將臨時值的指針成員置空cout << "mv" << this << endl;}~Test(){if(d != NULL){delete d;cout << "delete d\n";}cout << "ds: " << this << endl;}int * d; };Test GetTmp() {Test h;cout << "Resource from " << __func__ << ": " << (void *)h.d << endl;return h; }int main() {Test&& obj = GetTmp();cout << "Resource from " << __func__ << ": " << (void *)obj.d << endl;return 0; }
?
int main() {//Test&& obj = GetTmp();Test obj = GetTmp();cout << "Resource from " << __func__ << ": " << (void *)obj.d << endl;return 0; }
?
總結
以上是生活随笔為你收集整理的c++ 11 移动语义的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: OPNsense 18.7.X汉化包发布
- 下一篇: CentOS安装Java JDK