Note that there are some explanatory texts on larger screens.

plurals
  1. POCopy constructor strange behavior when returning-by-value
    text
    copied!<p>I tested the behavior of copy constructor with functions that return an object by value, and I came across a case where copy constructor does get invoked and a case it doesn't.</p> <p>Please consider the following code:</p> <pre><code>class A { public: A() {} A(const A&amp; a) { cout &lt;&lt; "Copy CTOR: " &lt;&lt; "This address is " &lt;&lt; this &lt;&lt; " input address is "&lt;&lt; &amp;a &lt;&lt; "\n"; } }; A returnMyself(A&amp; a) { cout&lt;&lt;"Myself address is: "&lt;&lt; &amp;a &lt;&lt; "\n"; return a; } A returnLocal(A&amp; a) { A local; cout&lt;&lt;"local address in returnLocal is "&lt;&lt; &amp;local &lt;&lt; "\n"; return local; } int main () { A a; cout&lt;&lt;"Before returnMyself\n"; returnMyself(a); cout&lt;&lt;"After returnMyself\n\n"; cout&lt;&lt;"Before returnLocal\n"; returnLocal(a); cout&lt;&lt;"After returnLocal\n"; } </code></pre> <p>The output of <code>main</code> is:</p> <pre> Before returnMyself. Myself address is: 0x7fff6afd88f0. Copy CTOR Invoked: This address is 0x7fff6afd88d8. Input address is 0x7fff6afd88f0. After returnMyself. Before returnLocal. Local address in returnLocal is 0x7fff6afd88d0. After returnLocal. </pre> <p>As you can see, when I declare a local object and return it, copy constructor doesn't get invoked, as opposed to returning a given reference-object which does invoke copy constructor.</p> <p>Does anyone have an explanation for this? In general, what are the cases of invoking copy constructor from a function that returns-by-value?</p> <p>Thanks!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload