Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Recommended reading: <a href="http://www.amazon.co.uk/Effective-Specific-Addison-Wesley-Professional-Computing/dp/0201924889" rel="noreferrer">Effective C++</a> by Scott Meyers. You find a very good explanation about this topic (and a lot more) in there.</p> <p>In brief, if you return by value, the copy constructor and the destructor will be involved by default (unless the compiler optimizes them away - that's what happens in some of your cases).</p> <p>If you return by reference (or pointer) a variable which is local (constructed on the stack), you invite trouble because the object is destructed upon return, so you have a dangling reference as a result.</p> <p>The canonical way to construct an object in a function and return it is by value, like:</p> <pre><code>MyClass fun() { return MyClass(a, b, c); } MyClass x = fun(); </code></pre> <p>If you use this, you don't need to worry about ownership issues, dangling references etc. And the compiler will most likely optimize out the extra copy constructor / destructor calls for you, so you don't need to worry about performance either.</p> <p>It is possible to return by reference an object constructed by <code>new</code> (i.e. on the heap) - this object will not be destroyed upon returning from the function. However, you have to destroy it explicitly somewhere later by calling <code>delete</code>.</p> <p>It is also technically possible to store an object returned by value in a reference, like:</p> <pre><code>MyClass&amp; x = fun(); </code></pre> <p>However, AFAIK there is not much point in doing this. Especially because one can easily pass on this reference to other parts of the program which are outside of the current scope; however, the object referenced by <code>x</code> is a local object which will be destroyed as soon as you leave the current scope. So this style can lead to nasty bugs.</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