简体   繁体   中英

Is C++ compiler allowed to optimize out unreferenced local objects

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();}
};

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.

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?

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 :

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.

It's perfectly safe to do that. In fact, it is an often used technique when putting in practice RAII. The compiler will not optimize out any local variable which has non-trivial constructor or destructor. Check out What is a non-trivial constructor in C++ .

To also avoid the compiler warning regarding unused local variables, you can use Q_UNUSED macro.

If you can observe any different the the compiler is not allowed to remove the object.

In this case the constructor/destructor have side effects, so the compiler will not remove them.

The idea of delegating effects to construction/destruction of local stack-based objects is used often; for example:

{
    Locker L(my_lock);
    ...
}

This way the code in ... will be executing with a lock being held, and the lock will be automatically released when you leave the scope for any reason (just getting out of the block, executing a return or and if exception is thrown while inside).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM