是否允许C ++编译器优化未引用的本地对象 [英] Is C++ compiler allowed to optimize out unreferenced local objects

查看:78
本文介绍了是否允许C ++编译器优化未引用的本地对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I use following class to automatically set waiting cursor in the beginning of a certain function and reset the cursor when function returns.

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

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

I create a local WaitCursorSetter object when function begins. Since waiting cursor is reset in the destructor of object, I do not have to reset the cursor before each and every return statement in the method since destructor gets called when function returns and object goes out of scope.

如果编译器优化了未引用的WaitCursorSetter对象,则此方法将无效.我的问题是,允许编译器优化此对象吗?

If the compiler optimized out the unreferenced WaitCursorSetter object, this will not work. My problem is, is the compiler allowed to optimize out this object?

推荐答案

不允许编译器优化自动对象,该对象的析构函数或初始化有副作用,我们可以通过标准草案部分3.7.3看到这一点. :

The compiler is not allowed to optimize away an automatic object whose destructors or initlization has side effects, we can see this by going to the draft standard section 3.7.3:

如果具有自动存储持续时间的变量具有初始化或 具有副作用的析构函数,不得在结束前销毁 的块,即使将其优化也不能消除 似乎未使用,除了类对象或其复制/移动可能 按照12.8的规定被淘汰.

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 ++编译器优化未引用的本地对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆