c++ - 为什么 gcc 会立即销毁我的对象,尽管它的范围? (我如何让它不那样做?)

标签 c++ optimization gcc destructor raii

我写了一个小的分析类和一个伴随的守卫类来使用这样的:

{
    ProfileGuard pg("SampleName");

    // Code to profile
    ...
}

但后来我注意到有时 gcc 会优化代码,以便 pg 立即被破坏。显然它检测到 pg 和其他代码不会相互影响。防止 gcc 这样做的最佳方法是什么?

更新: 由于对我的问题有一些严重的怀疑,我将再次检查我的代码。我的问题基于:

3.7.3 3.

If a variable with automatic storage duration has initialization or a destructor with side effects, it shall not be destroyed before the end of its block, nor shall it be eliminated as an optimization even if it appears to be unused, except that a class object or its copy/move may be eliminated as specified in 12.8.

打印是“副作用”吗?

最佳答案

Apparently it detects that pg and the other code will not influence eachother.

怎么会,既然这显然是不真实的?它们确实相互影响(例如通过输出顺序)。

GCC 不会这样做。也许您不小心使用了匿名(因此是临时的)对象?

ProfileGuard("SampleName");

现在,这个在执行表达式后立即被销毁。

关于c++ - 为什么 gcc 会立即销毁我的对象,尽管它的范围? (我如何让它不那样做?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7470913/

相关文章:

c++ - C++中的循环优化技术

MySQL更新1个查询或多个查询

sql - 左联接是我想要的,但是速度很慢?

c++ - 需要解释 C++ 代码的行为

c - 转换为 void 时的警告**

c++ - C 中的 undefined reference 错误

c++ - 如何通过复制内存序列化 C++ 中的对象?

c++ - g++ 4.4 const var 段错误的取消引用更改

algorithm - 子数组查询

c - gcc的目录结构