I'm sure this topic would have been discussed many times but I am having difficulty finding the information.
What is the best way to return a string or object from a function? I don't want the calling function to be responsible for the disposal of the object. I wrote little test program to try work it out and came up with.
Which results in:
before constructor
constructing 2293536
after constructor
bam
destructing 2293536
So the object is not destroyed when it is passed back into the main function... other methods clearly destroy the object before it is returned. So, is this the best way of doing this and are there any good websites that explain how C++ compilers handle functions that return objects created within the function?
In the above code, with no optimizations, the compiler creates result on the stack inside foo() and then the value is "returned". Returning it in this case means that hw is assigned the returned value, possibly through operator= or the copy constructor; likely the latter) and then "result" is destroyed.
You haven't lost data; it was just transferred from one location to another.
With optimizations turned on, assuming my foo() did something more than it does, the same thing will occur. However, with optimizations turned on, your x() function is so trivial that the compiler is using an optimization technique called Return Value Optimzation (RVO) wherein the local variable (also named x) is actually constructed in the same memory location (stack location) occupied by main()'s local variable a. Which means that when x() returns, no copying is needed since there isn't really a second (temporary) instance, and therefore no destructor needs to run.