Synchronizing access to a return value Synchronizing access to a return value multithreading multithreading

Synchronizing access to a return value


Both of your example constructs will do what you're looking for. The following information from the standard supports the behavior you're looking for (even in your 1st example):

12.4/10 Destructors:

Destructors are invoked implicitly ... for a constructed object with automatic storage duration (3.7.2) when the block in which the object is created exits.

And, 6.6/2 Jump statements (of which return is one):

On exit from a scope (however accomplished), destructors (12.4) are called for all constructed objects with automatic storage duration (3.7.2) (named objects or temporaries) that are declared in that scope, in the reverse order of their declaration. Transfer out of a loop, out of a block, or back past an initialized variable with automatic storage duration involves the destruction of variables with automatic storage duration that are in scope at the point transferred from but not at the point transferred to.

So at the point of the return the lock variable is in scope and therefore the dtor has not been called. Once the return has been executed, the dtor for the lock variable is called (thus releasing the lock).


Your first variant is safe, however you can't rely on this returned value to be consistent for any period of time. I mean for example don't use that returned value in a for loop to iterate over each element, because the real size could change right after the return.

Basically you can think of it like this: a copy is needed of the return value, otherwise the destructor would be called hence possibly corrupting whatever the return value was before it was returned.

The destructor is called after the return statement.Take this equivalent example:

#include <assert.h>class A{public:    ~A()    {        x = 10;    }    int x;};int test(){    A a;    a.x = 5;    return a.x;}int main(int argc, char* argv[]){    int x = test();    assert(x == 5);    return 0;}


Your initial code is fine - the destructor will be called after the return value has been stored. This is the very principle RAII operates on!