c++ - 是否允许 C++ 编译器优化未引用的本地对象

标签 c++ qt optimization

我使用以下类在某个函数的开头自动设置等待光标,并在函数返回时重置光标。

class WaitCursorSetter
{
public:
    WaitCursorSetter() {QApplication::setOverrideCursor(Qt::WaitCursor);}
    virtual ~WaitCursorSetter() {QApplication::restoreOverrideCursor();}
};

我在函数开始时创建一个本地 WaitCursorSetter 对象。由于在对象的析构函数中重置了等待游标,因此我不必在方法中的每个返回语句之前重置游标,因为当函数返回并且对象超出范围时会调用析构函数。

如果编译器优化掉未引用的 WaitCursorSetter 对象,这将不起作用。我的问题是,是否允许编译器优化这个对象?

最佳答案

编译器不允许优化掉其析构函数或初始化有副作用的自动对象,我们可以通过标准草案 3.7.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.

关于c++ - 是否允许 C++ 编译器优化未引用的本地对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27741698/

相关文章:

c++ - 什么是处理 bool 代数方程的良好数据结构?

python - 是否可以让 QWebKit 显示 pdf 文件?

python - matplotlib 茎图的优化

url - SEO URL 的区别/和/index.php

c# - C#-fu-以功能样式查找常用单词

c++ - const 和非常量迭代器的一个类。是否可以?

c++ - 具有静态成员实例的单例

c++ - Qt.pro 文件 : adding path which includes "include" directory doesn't work

c++ - 将类添加到基本 Qt GUI 应用程序时出现 Qt 链接器错误

c++ - 在屏幕右侧显示主窗口(Qt 5.1.0)