C++ Raii 和堆栈展开

发布于 2024-09-08 02:45:17 字数 264 浏览 6 评论 0原文

(我修改了原来的问题,使其更有意义)

关于 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

烟雨扶苏 2024-09-15 02:45:17

要回答您修改后的问题,请给出代码:

return X;

X 将始终在返回发生之前进行评估。然后发生的情况相当于函数的所有嵌套作用域都被退出,按从最内到最外的顺序,并在每次退出时适当地调用析构函数。

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.

橘和柠 2024-09-15 02:45:17

您可以通过使用析构函数编写自己的简单类来轻松测试这一点,例如

class X
   {
   public:
      ~X() { std::cout << "X::destructor" << std::endl;
   }

size_t advance()
   {
   X x;
   return value++;
   }

在 X 的析构函数中放置一个中断,然后查看此时值是否已增加。您还可以尝试使用 /FA (Visual Studio) 进行编译,并查看编译器生成了哪个程序集。

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.

一身软味 2024-09-15 02:45:17

是的 - 它们是等价的。锁在增量后被销毁。否则你在后面的案例中也会遇到同样的问题。

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文