Note that there are some explanatory texts on larger screens.

plurals
  1. POC++: returning by reference and copy constructors
    primarykey
    data
    text
    <p>References in C++ are baffling me. :)</p> <p>The basic idea is that I'm trying to return an object from a function. I'd like to do it without returning a pointer (because then I'd have to manually <code>delete</code> it), and without calling the copy-constructor, if possible (for efficiency, naturally <strong>added:</strong> and also because I wonder if I can't avoid writing a copy constructor).</p> <p>So, all in all, here are the options for doing this that I have found:</p> <ul> <li>The function return type can be either the class itself (<code>MyClass fun() { ... }</code>) or a reference to the class (<code>MyClass&amp; fun() { ... }</code>).</li> <li>The function can either construct the variable at the line of return (<code>return MyClass(a,b,c);</code>) or return an existing variable (<code>MyClass x(a,b,c); return x;</code>).</li> <li>The code that receives the variable can also have a variable of either type: (<code>MyClass x = fun();</code> or <code>MyClass&amp; x = fun();</code>)</li> <li>The code which receives the variable can either create a new variable on the fly (<code>MyClass x = fun();</code>) or assign it to an existing variable (<code>MyClass x; x = fun();</code>)</li> </ul> <p>And some thoughts on that:</p> <ul> <li>It seems to be a bad idea to have the return type <code>MyClass&amp;</code> because that always results in the variable being destroyed before it gets returned.</li> <li>The copy constructor only seems to get involved when I return an existing variable. When returning a variable constructed in the line of return, it never gets called.</li> <li>When I assign the result to an existing variable, the destructor also always kicks in before the value is returned. Also, no copy constructor gets called, yet target variable does receive the member values of the object returned from the function.</li> </ul> <p>These results are so inconsistent that I feel totally confused. So, what EXACTLY is happening here? How should I properly construct and return an object from a function?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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