我使用以下类在某个函数的开头自动设置等待光标,并在函数返回时重置光标。
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/