tags:

views:

103

answers:

3

hello

(I modified the original question to be more meaningful)

With respect to return statement, are Raii object destroyed before/after/between return statement?

for example

size_t advance() {
    boost::lock_guard<boost::mutex> lock(mutex_);
    return value_++;  // is lock destroyed after increment?
}

thank you

A: 

Yes - they are equivalent. Lock is destroyed after increment. Otherwise you would have the same problem with the later case.

agsamek
+1  A: 

You can test this easily by writing your own simple class with a destructor, e.g.

class X
   {
   public:
      ~X() { std::cout << "X::destructor" << std::endl;
   }

size_t advance()
   {
   X x;
   return value++;
   }

Put a break in the destructor of X, and see if value has already been incremented at that moment. You may also try to compile using /FA (Visual Studio) and see which assembly is generated by the compiler.

Patrick
so, stack is unwound (hope its correct word) after return statement?
aaa
I would expect this, but to be sure, you have to try it.
Patrick
@Patrick "try it" is the worst way to check up on a language feature. Th C++ Standard says that x will be destroyed when the return is encountered - any compiler that emitted code that didn't do this would not be a C++ compiler.
anon
@Neil, I agree, but C++ has quite some subtleties it can be easier to just try it instead of guessing what is intended in the C++ standard. I also think that it can be more 'therapeutical' to try it yourself. It's easier to remember something if you tried it yourself rather than something you read in a book.
Patrick
+2  A: 

To answer your modified question, given the code:

return X;

X will always be evaluated before the return takes place. Then what happens is equivalent to all the nested scopes of the function being exited, in order from inmost to outmost, with destructors being called appropriately at each exit.

anon