C++中返回对象的情形及RVO
生活随笔
收集整理的這篇文章主要介紹了
C++中返回对象的情形及RVO
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
http://www.cnblogs.com/xkfz007/archive/2012/07/21/2602110.html
?
之前有文章介紹過臨時對象和返回值優(yōu)化RVO方面的問題。見此處。
在C++中,返回對象這一點經(jīng)常被詬病,因為這個地方的效率比較低,需要進(jìn)行很多的操作,生成一些臨時對象,如果對象比較大的會就會比較耗時。但是在編譯器實現(xiàn)的時候,經(jīng)常是對返回對象的情況進(jìn)行優(yōu)化,也就是進(jìn)行返回值優(yōu)化?。
在g++中,這個是默認(rèn)已經(jīng)進(jìn)行了優(yōu)化。以前我希望看看到底C++怎么操作的,但是無法看到,就是因為G++進(jìn)行了默認(rèn)的返回值優(yōu)化RVO。今天在晚上發(fā)現(xiàn)可以有一中方法來禁止這個RVO,可以參考這兒。
具體來說就是在編譯的時候,加上-fno-elide-constructors這個選項,
?
#include <iostream> using namespace std;class HasPtrMem { public:HasPtrMem(): d(new int(3)) {cout << "Construct: " << ++n_cstr << endl;}HasPtrMem(const HasPtrMem & h): d(new int(*h.d)) {cout << "Copy construct: " << ++n_cptr << endl;}HasPtrMem(HasPtrMem && h): d(h.d) { // 移動構(gòu)造函數(shù)h.d = nullptr; // 將臨時值的指針成員置空cout << "Move construct: " << ++n_mvtr << endl;}~HasPtrMem() {delete d;cout << "Destruct: " << ++n_dstr << endl;}int * d;static int n_cstr;static int n_dstr;static int n_cptr;static int n_mvtr; };int HasPtrMem::n_cstr = 0; int HasPtrMem::n_dstr = 0; int HasPtrMem::n_cptr = 0; int HasPtrMem::n_mvtr = 0;HasPtrMem GetTemp() {HasPtrMem h;cout << "Resource from " << __func__ << ": " << hex << h.d << endl;return h; }int main() {HasPtrMem a = GetTemp();cout << "Resource from " << __func__ << ": " << hex << a.d << endl; }?
編譯執(zhí)行:
g++ std_move4.cpp -std=c++11$./a.out Construct: 1 Resource from GetTemp: 0x2572010 Resource from main: 0x2572010 Destruct: 1?
添加?-fno-elide-constructors 選項,然后編譯執(zhí)行
$g++ std_move4.cpp -std=c++11 -fno-elide-constructors$./a.out Construct: 1 Resource from GetTemp: 0x6e7010 Move construct: 1 Destruct: 1 Move construct: 2 Destruct: 2 Resource from main: 0x6e7010 Destruct: 3可以清晰的看到兩次?Move construct 的執(zhí)行
?
總結(jié)
以上是生活随笔為你收集整理的C++中返回对象的情形及RVO的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 绝对定位元素设置水平居中
- 下一篇: 我想成为怎样的人?