Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If you're talking about for example <code>operator+</code>, where the object returned is not either of those input, then the answer is you instantiate on the stack and return by value:</p> <pre><code>struct SomeClass { int value; }; SomeClass operator+(const SomeClass &amp;lhs, const SomeClass &amp;rhs) { SomeClass retval; retval.value = lhs.value + rhs.value; return retval; } </code></pre> <p>or</p> <pre><code>class SomeClass { int value; public: SomeClass operator+(const SomeClass &amp;rhs) const { SomeClass retval; retval.value = this-&gt;value + rhs.value; return retval; } }; </code></pre> <p>or even:</p> <pre><code>class SomeClass { int value; public: SomeClass(int v) : value(v) {} friend SomeClass operator+(const SomeClass &amp;lhs, const SomeClass &amp;rhs) { return SomeClass(lhs.value + rhs.value); } }; </code></pre> <p>The compiler then worries about where (on the stack) the return value is actually stored.</p> <p>It will for example apply return-value optimizations if it can, but in principle what's happening is "as-if" the work you do constructs some value on the stack of your operator overload, and then at return this is copied to wherever it needs to be next. If the caller assigns the return value, it's copied there. If the caller passes it by value to some other function, it's copied wherever the calling convention says it needs to be in order to be that function parameter. If the caller takes a const reference, then it's copied to a temporary hidden away on the stack.</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