贴下例子和结果,具体就不分析了。感觉自己还是有点一知半解,而且是跟编译器有关的,我只拿gcc测试了下。

例子:

#include <iostream>

using namespace std;

class CA {

public:

CA()

{

cout << "construct\t" << this << endl;

}

CA(const CA& ca)

{

cout << "copy construct\t" << this << "\tfrom\t" << &ca<< endl;

}

void operator=(const CA&)

{

cout << "assignment function\t" << this << endl;

}

~CA()

{

cout << "deconstruct\t" << this << endl;

}

};

CA fRVO()

{

return CA();

}

CA fNRVO()

{

cout << "fNRVO begin" << endl;

CA a;

cout << "fNRVO end" << endl;

return a;

}

int main(void)

{

CA a = CA();

cout << &a << endl;

cout << "----------------------------------" << endl;

CA b = fRVO();

cout << &b << endl;

cout << "----------------------------------" << endl;

CA c = fNRVO();

cout << &c << endl;

cout << "----------------------------------" << endl;

return 0;

}


输出:

$ g++ RVOANDNRVO.cpp -fno-elide-constructors

$ ./a.out

construct 0xbfbcbbba

copy construct 0xbfbcbbbb from 0xbfbcbbba

deconstruct 0xbfbcbbba

0xbfbcbbbb

----------------------------------

construct 0xbfbcbb7f

copy construct 0xbfbcbbb8 from 0xbfbcbb7f

deconstruct 0xbfbcbb7f

copy construct 0xbfbcbbb9 from 0xbfbcbbb8

deconstruct 0xbfbcbbb8

0xbfbcbbb9

----------------------------------

fNRVO begin

construct 0xbfbcbb7f

fNRVO end

copy construct 0xbfbcbbb6 from 0xbfbcbb7f

deconstruct 0xbfbcbb7f

copy construct 0xbfbcbbb7 from 0xbfbcbbb6

deconstruct 0xbfbcbbb6

0xbfbcbbb7

----------------------------------

deconstruct 0xbfbcbbb7

deconstruct 0xbfbcbbb9

deconstruct 0xbfbcbbbb

$ g++ RVOANDNRVO.cpp

$ ./a.out

construct 0xbfcbe45b

0xbfcbe45b

----------------------------------

construct 0xbfcbe45a

0xbfcbe45a

----------------------------------

fNRVO begin

construct 0xbfcbe459

fNRVO end

0xbfcbe459

----------------------------------

deconstruct 0xbfcbe459

deconstruct 0xbfcbe45a

deconstruct 0xbfcbe45b