Search code examples
c++scoperaii

C++ Raii and stack unwinding


(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


Solution

  • 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.