RVO in C++
Im folgenden Beispiel scheint es zwei Objekte zu geben: »x« und »o«.
Eine Optimierungstechnik, die RVO (return-value optimization ) führt aber dazu, daß es nur ein Objekt gibt, nämlich »o«.
Da der Kompiler erkennen kann, daß der Wert aus »x« ohnehin in »o« endet, wird beim Aufruf von »f()« als Speicherplatz für »x« gleich der Speicherplatz von »o« genommen.
main.cpp
void f()
{ object x;
return x; }int main()
{ object o = f(); }
Das folgende Programm zeigt, daß es nur ein Objekt gibt, indem es nur eine einzige Adresse ausgibt.
main.cpp
#include <string>
#include <iostream>
#include <ostream>
using namespace ::std::literals;
struct object
{ ::std::string name;
void dump( ::std::string const & what )
{ ::std::clog << what << this->name <<
" at "s << static_cast< void * >( this )<< '\n'; }void info()
{ dump( "info: "s ); }void info( ::std::string const & label )
{ dump( label + " is "s ); }explicit object( ::std::string s ): name( ::std::move( s ))
{ dump( "constructing to "s ); }object( const object & a ): name( a.name )
{ dump( "copying to " ); }object( object && a )noexcept : name( ::std::move( a.name ))
{ dump( "moving to " ); }object& operator +=( object const & other )
{ ::std::clog << "### appending "s << name << ' ' <<
static_cast< void * >( this ) << " + " << other.name <<
' ' << static_cast< void const * >( &other )<< " to "s <<
static_cast< void * >( this )<< '\n';name += other.name;
return *this; }};
static object f()
{ object x{ "A"s };
x.info( "x"s );
return x; }int main()
{ object o = f();
o.info( "o"s ); }transcript
constructing to A at 0x22fdb0
x is A at 0x22fdb0
o is A at 0x22fdb0—
—
—