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.


It's guaranteed. The return value is copied (if necessary) before the destruction occurs. Here's a similar question / answer that gives a good description of the sequence.

Scope and return values in C++

Tags:

C++

Locking