Search code examples
c++optimizationraiiside-effects

C++ optimizer removal of object with side effects


This is not currently a problem, but I am concerned if the code gets ported or we change compilers.

I have code with a block

{ 
   MyClass myObj;
   // copy some other variables but never touch myObj
   .
   .
} // expect destructor to be called on myObj

where myObj is never used in the block code but the constructor has a side effect and I rely on the destructor code of MyClass to be executed at the close of the block. This works as expected on my current arm compiler with some optimization turned on.

My question is, is there any thing I need to do, like declaring something volatile or setting some common attribute to prevent an optimizer from detecting myObj as an unused variable or some such.

This is not a C++11 compiler. As I said this is not currently a problem but I did not want to leave an odd future bug for someone else.


Solution

  • Apart from explicitly defined cases like RVO (return value optimization), optimization is not allowed to change the observable behaviour of the program. Optimizations must follow the so called "as-if" rule.