Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
632 views
in Technique[技术] by (71.8m points)

qt - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...