我写了一个小的分析类和一个伴随的守卫类来使用这样的:
{
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/