0

(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

Anycorn
  • 50,217
  • 42
  • 167
  • 261

3 Answers3

2

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.

1

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
  • 23,217
  • 12
  • 67
  • 130
  • so, stack is unwound (hope its correct word) after return statement? – Anycorn Jul 03 '10 at 20:43
  • I would expect this, but to be sure, you have to try it. – Patrick Jul 03 '10 at 20:44
  • 3
    "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. –  Jul 03 '10 at 20:54
  • @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 Jul 04 '10 at 11:54
0

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

agsamek
  • 8,734
  • 11
  • 36
  • 43