自动对象销毁 [英] Automatic object destruction

查看:52
本文介绍了自动对象销毁的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否保证自动对象(在堆栈上创建的对象)的销毁不会在超出范围之前执行?

Is the destruction of automatic objects (objects created on the stack) guaranteed to be executed not before they go out of scope?

澄清:

#include <iostream>

class A {
  public:
    A() {
      std::cout << "1";
    }
    ~A() {
      std::cout << "3";
    }
};

void test123() {
  A a;
  std::cout << "2";
}

打印"2",不再需要a,所以理论上编译器可以尽快优化和销毁a因为不再需要它了.

To print "2", a is not required any more, so theoretically the compiler could try to optimise and destroy a as soon as it is not needed any more.

我可以依靠上面的功能总是打印123吗?

Can I rely on the above function always printing 123?

推荐答案

栈对象的销毁顺序是严格定义的——当你离开作用域时(或者通过运行结束{},或通过 return,或通过异常).因此,您将总是在那里看到 123.

The destruction order of stack objects is strictly defined - they execute in reverse order of declaration, when you leave the scope (either by running off the end of the {}, or by return, or by an exception). So, you will always see 123 there.

但是请注意,编译器优化受as-if"规则的约束.换句话说,编译器可以提前销毁一个对象,只要生成的程序表现得好像"它在正常时间被销毁了.在这种情况下,因为您进行输出,所以编译器必须在适当的时间安排输出.但是,例如,如果您拥有指向原始类型的 deleteda 指针,并且编译器可以证明没有其他未完成的指向该值的指针,则原则上它可以移动该 早点删除.关键是没有符合标准的程序能够注意到这种优化.

Note, however, that compiler optimizations are governed by the 'as-if' rule. In other words, a compiler can destroy an object early, as long as the resulting program behaves 'as-if' it had been destroyed at the normal time. In this case, because you do output, the compiler must schedule the output at the proper time. However, if you had, for example, deleted a pointer to a primitive type, and the compiler can prove there are no other outstanding pointers to that value, it could, in principle, move that delete earlier. The key is that no conforming program is capable of noticing this optimization.

这篇关于自动对象销毁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆