C++ Raii 和堆栈展开
(我修改了原来的问题,使其更有意义)
关于 return 语句,Raii 对象在 return 语句之前/之后/之间是否被销毁?
例如
size_t advance() {
boost::lock_guard<boost::mutex> lock(mutex_);
return value_++; // is lock destroyed after increment?
}
谢谢
(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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
要回答您修改后的问题,请给出代码:
X 将始终在返回发生之前进行评估。然后发生的情况相当于函数的所有嵌套作用域都被退出,按从最内到最外的顺序,并在每次退出时适当地调用析构函数。
To answer your modified question, given the code:
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.
您可以通过使用析构函数编写自己的简单类来轻松测试这一点,例如
在 X 的析构函数中放置一个中断,然后查看此时值是否已增加。您还可以尝试使用 /FA (Visual Studio) 进行编译,并查看编译器生成了哪个程序集。
You can test this easily by writing your own simple class with a destructor, e.g.
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.