C++ return local object

Viewed 11885

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;
}
8 Answers

It's ok for a function to "return a local object", because the compiler will transform the function to not really return a value. Instead, it will accept a reference MyObject& __result, and use the local object which will be assigned the return value, i.e. obj, to copy construct the __result. In your case, the function will be rewritten to:

static void createMyObject(MyObject& __result) {
    MyObject obj;

    // .. process obj
    // compiler generated invocation of copy constructor
    __result.MyObject::Myobject( obj );

    return;
}

and every invocation of createMyObject will also be transformed to bind the reference to an existing object. For example, an invocation of the form:

MyObject a = createMyObject();

will be transformed to:

MyObject a;  // no default constructor called here
createMyObject(a);

However, if you return a reference or pointer to a local object, the compiler cannot fulfill the transform. You will be returning a reference or pointer to a already-destroyed object.

Related