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;
}
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.