简体   繁体   English

C ++ Raii和堆栈展开

[英]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? 关于返回语句,是否在返回语句之前/之后/之间销毁了Raii对象?

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. X将始终在返回发生之前求值。 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, eg 您可以通过使用析构函数编写您自己的简单类来轻松地对此进行测试,例如

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. 在X的析构函数中放置一个中断,然后看值在那时是否已经增加。 You may also try to compile using /FA (Visual Studio) and see which assembly is generated by the compiler. 您也可以尝试使用/ FA(Visual Studio)进行编译,并查看编译器生成的程序集。

Yes - they are equivalent. 是的-它们是等效的。 Lock is destroyed after increment. 增量后锁被销毁。 Otherwise you would have the same problem with the later case. 否则,后面的情况将有相同的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM