c++ 11 移动语义
生活随笔
收集整理的這篇文章主要介紹了
c++ 11 移动语义
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
C++?已經(jīng)擁有了拷貝構(gòu)造函數(shù),?和賦值函數(shù),它們主要定位為淺和深度拷貝,?新增加一個移動構(gòu)造函數(shù),主要避免拷貝構(gòu)造。
在定義了移動構(gòu)造函數(shù)的情況下,在實參(argument)是一個右值(rvalue,包括xvalue和prvalue)的情況下會調(diào)用移動構(gòu)造函數(shù),而不是調(diào)用復(fù)制構(gòu)造函數(shù)?
可以使用std::move語句可以將左值變?yōu)橛抑刀苊饪截悩?gòu)造,修改代碼如下:
編譯器會對返回值進行優(yōu)化,簡稱RVO,是編譯器的一項優(yōu)化技術(shù),它涉及(功能是)消除為保存函數(shù)返回值而創(chuàng)建的臨時對象。
-fno-elide-constructors,此選項作用是,在 g++ 上編譯時關(guān)閉 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) // { // 移動構(gòu)造函數(shù) // 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){ // 移動構(gòu)造函數(shù)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; }
?
總結(jié)
以上是生活随笔為你收集整理的c++ 11 移动语义的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: OPNsense 18.7.X汉化包发布
- 下一篇: CentOS安装Java JDK