RVO in C++ [] (RVO in C++), Programm, Seite 723052
https://www.purl.org/stefan_ram/pub/rvo_c++ (Permalink) ist die kanonische URI dieser Seite.
Stefan Ram
C++-Kurs

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

Seiteninformationen und Impressum   |   Mitteilungsformular  |   "ram@zedat.fu-berlin.de" (ohne die Anführungszeichen) ist die Netzpostadresse von Stefan Ram.   |   Eine Verbindung zur Stefan-Ram-Startseite befindet sich oben auf dieser Seite hinter dem Text "Stefan Ram".)  |   Der Urheber dieses Textes ist Stefan Ram. Alle Rechte sind vorbehalten. Diese Seite ist eine Veröffentlichung von Stefan Ram. Schlüsselwörter zu dieser Seite/relevant keywords describing this page: Stefan Ram Berlin slrprd slrprd stefanramberlin spellched stefanram723052 stefan_ram:723052 RVO in C++ Stefan Ram, Berlin, and, or, near, uni, online, slrprd, slrprdqxx, slrprddoc, slrprd723052, slrprddef723052, PbclevtugFgrsnaEnz Erklärung, Beschreibung, Info, Information, Hinweis,

Der Urheber dieses Textes ist Stefan Ram. Alle Rechte sind vorbehalten. Diese Seite ist eine Veröffentlichung von Stefan Ram.
https://www.purl.org/stefan_ram/pub/rvo_c++