Several co-workers and I are having a debate about what happens when a local variable (allocated on the stack) is returned from a C++ method.
The following code works in a unit test, but I believe that is only because the unit test is lucky and doesn't attempt to reuse the memory on the stack used by obj.
Does this work?
static MyObject createMyObject() { MyObject obj; return obj; }
Yes you are returning an array, which is actually a pointer behind the scenes, to the address of the memory location where the contents of the variable you've initialised is stored.
If a method or function returns a local object, it should return an object, not a reference. If a method or function returns an object of a class for which there is no public copy constructor, such as ostream class, it must return a reference to an object.
It would mean make a copy and return it. The difference is that if you return pointer to objects internal variable that object state could be modified from outside. If you return copy that copy can be modified and the original object will not change.
Returning Object as argumentobject = return object_name; Example: In the above example we can see that the add function does not return any value since its return-type is void. In the following program the add function returns an object of type 'Example'(i.e., class name) whose value is stored in E3.
What happens is that the copy constructor gets called to make a copy of the local object, and that is what the caller receives.
The compiler may eliminate the copy in a process called copy elision, but that's at the discretion of the compiler - you don't have much control over it.
This pattern is capable of producing the problems you're afraid of, but only if you're returning a pointer or reference to the local object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With