简体   繁体   English

是否可以优化“未使用”的对象?

[英]Can an “unused” object be optimized away?

In code like this: 在这样的代码中:

void foo() {
  SomeObject obj;
}

one might argue that obj is "unused" and therefore can be optimized away, just like an unused local int might be. 有人可能会说obj是“未使用的”,因此可以进行优化,就像未使用的本地int一样。 That seems like an error to me though, because unlike with an int , there could be important side effects of the SomeObject constructor. 不过,这对我来说似乎是一个错误,因为与int不同, SomeObject构造函数可能会有重要的副作用。 So, I am wondering, does the language explicitly require that such local variables not be optimized away? 因此,我想知道,该语言是否明确要求不要优化此类局部变量? Or does a programmer have to take precautions to prevent such optimization? 还是程序员必须采取预防措施来防止这种优化?

If the compiler has the definition of the SomeObject::SomeObject() constructor and the SomeObject destructor available (ie if they're defined inline) and can see there are no side effects, then yes, this can be optimised out (provided you don't do anything else with obj that requires it to be fully constructed.) 如果编译器具有SomeObject::SomeObject()构造函数的定义和SomeObject析构函数的可用定义(即,如果它们是内联定义的)并且可以看到没有副作用,那么可以进行优化(前提是您不这样做)不需要对其进行完全构造的obj做其他任何事情。)

Otherwise, if the constructor is defined in another translation unit, then the compiler can't know that there are no side effects, so the call will be made (and the destructor too, if that's not inline). 否则,如果构造函数是在另一个转换单元中定义的,则编译器将不知道没有副作用,因此将进行调用(如果不是内联的,则进行析构函数的调用)。

In general, the compiler is at liberty to perform any optimisation that doesn't alter the semantics of the program. 通常,编译器可以自由执行任何不会改变程序语义的优化。 In this case, removing an unused local variable whose constructor and destructor do not touch any other code won't alter the meaning of your program, so it's perfectly safe to do. 在这种情况下,删除一个未使用的局部变量,该局部变量的构造函数和析构函数不接触任何其他代码,不会改变程序的含义,因此这样做是绝对安全的。

First, let's correct the example: 首先,让我们更正示例:

void foo() {
  SomeObject obj; // not obj()
}

Second, 'as-if' rule applies to optimizers. 其次,“按需”规则适用于优化程序。 Thus, it might optimize out the entire object, however, all side effect(s) of constructor(s) / destructor(s), including base class(es) must show up. 因此,它可能会优化整个对象,但是必须显示出构造函数/析构函数的所有副作用,包括基类。 This means that it's possible that you end up not using additional memory (as long as you don't take the address of obj), but your constructor(s) / destructor(s) will still run. 这意味着您有可能最终不使用额外的内存 (只要您不使用obj的地址),但构造函数/析构函数仍将运行。

Yes. 是。 Modern compilers are pretty good at removing dead code (assuming you build with optimizations enabled). 现代编译器非常擅长删除无效代码(假设您在启用优化的情况下进行构建)。 That includes unused objects - if the constructor and destructor does not have side effects and the compiler can see that (as in; it's not hidden away in a library). 这包括未使用的对象-如果构造函数和析构函数没有副作用,并且编译器可以看到该副作用(例如,它没有隐藏在库中)。

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

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