Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 618
Lahiru Chandima Avatar asked Jan 02 '15 11:01

Lahiru Chandima


People also ask

What is compiler optimization in C?

Compiler optimization is generally implemented using a sequence of optimizing transformations, algorithms which take a program and transform it to produce a semantically equivalent output program that uses fewer resources or executes faster.

Does gcc optimize by default?

GCC has a range of optimization levels, plus individual options to enable or disable particular optimizations. The overall compiler optimization level is controlled by the command line option -On, where n is the required optimization level, as follows: -O0 . (default).

What optimization does gcc do?

The compiler optimizes to reduce the size of the binary instead of execution speed. If you do not specify an optimization option, gcc attempts to reduce the compilation time and to make debugging always yield the result expected from reading the source code.

How does the C++ compiler optimize?

The C/C++ compiler compiles each source file separately and produces the corresponding object file. This means the compiler can only apply optimizations on a single source file rather than on the whole program. However, some important optimizations can be performed only by looking at the whole program.


1 Answers

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.

like image 182
Shafik Yaghmour Avatar answered Nov 10 '22 19:11

Shafik Yaghmour