References in C++ are baffling me. :)
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 delete
it), and without calling the copy-constructor, if possible (for efficiency, naturally added: and also because I wonder if I can't avoid writing a copy constructor).
So, all in all, here are the options for doing this that I have found:
MyClass fun() { ... }
) or a reference to the class (MyClass& fun() { ... }
).return MyClass(a,b,c);
) or return an existing variable (MyClass x(a,b,c); return x;
).MyClass x = fun();
or MyClass& x = fun();
)MyClass x = fun();
) or assign it to an existing variable (MyClass x; x = fun();
)And some thoughts on that:
MyClass&
because that always results in the variable being destroyed before it gets returned.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?
The best way to understand copying in C++ is often NOT to try to produce an artificial example and instrument it - the compiler is allowed to both remove and add copy constructor calls, more or less as it sees fit.
Bottom line - if you need to return a value, return a value and don't worry about any "expense".