C++ return value created before or after auto var destruction?

Yes, the auto variable will remain in scope until after the return is finished. This is especially true if you are using a compiler that optimizes the return, eg:

Gift get() 
{ 
    Lock lock(mutex);
    return gift;
} 

Gift g = basket.get();

Which would be equivilent to this sequence:

Gift g;
Lock lock(mutex);
g = Gift(gift);
lock.~Lock();

May be optimized to act more like this:

void get(Gift &ret) 
{ 
    Lock lock(mutex);
    ret = gift;
} 

Gift g;
basket.get(g);

Which would be equivilent to this sequence:

Gift g;
Lock lock(mutex);
g = gift;
lock.~Lock();

In other words, a temporary can be removed during the return.

Leave a Comment