C++ Raii and stack unwinding
(I modified the orig开发者_JS百科inal 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
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.
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.
Yes - they are equivalent. Lock is destroyed after increment. Otherwise you would have the same problem with the later case.
精彩评论