"Panjandrum " <pa********@spa mbob.com> schrieb:
vector<int> f()
{
return vector<int>;
}
This will create a copy of the entire vector while the temporary
object will soon be forgotten unless the compiler supports a
return value optimization.
Even _with_ RVO
vector<int> x = f()
will copy the vector twice.
I had this in another news group some days ago. Look at the following
program:
#include <iostream>
using namespace std;
struct X
{
X() { cout << "X"; }
X( const X& ) { cout << "C"; }
};
X f()
{
return X();
}
X g()
{
X x;
return x;
}
#define TEST( code ) \
cout << #code << "\t: "; code; cout << endl
int main()
{
TEST( X x1( f() ); );
TEST( X x2( g() ); );
TEST( X const& x3 = f(); );
TEST( X const& x4 = g(); );
}
This little program compiles indeed different with several compilers.
I used the one I had on my machine. Look at this:
------------------------------------------------------------------------
MSVC 6
X x1( f() ); : X
X x2( g() ); : XC
X const& x3 = f(); : X
X const& x4 = g(); : XC
------------------------------------------------------------------------
MSVC 7.1
X x1( f() ); : X
X x2( g() ); : XC
X const& x3 = f(); : X
X const& x4 = g(); : XC
------------------------------------------------------------------------
gcc 3.2.3 (mingw)
X x1( f() ); : X
X x2( g() ); : X
X const& x3 = f(); : X
X const& x4 = g(); : X
------------------------------------------------------------------------
aCC (HP ANSI C++ B3910B A.03.27, HPUX)
X x1( f() ); : XC
X x2( g() ); : XCC
X const& x3 = f(); : X
X const& x4 = g(); : XC
------------------------------------------------------------------------
gcc does never (!) copy. Also the Microsoft compilers do avoid the
copy during return. They copy just the local variable. aCC on HPUX
does indeed copy during return. Because of this differences I would
not use this method of returning an object.
T.M.