3

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.

Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
bd2357
  • 704
  • 9
  • 17
  • 2
    A non-trivial constructor or destructor should be sufficient to prevent the optimizer from eliminating it. – Dark Falcon May 29 '15 at 18:12
  • See possible duplicate [Is C++ compiler allowed to optimize out unreferenced local objects](http://stackoverflow.com/q/27741698/1708801) – Shafik Yaghmour Jun 11 '15 at 19:45

2 Answers2

3

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.

Community
  • 1
  • 1
hyde
  • 60,639
  • 21
  • 115
  • 176
  • I didn't know about RVO, but the idea of side effects in a copy constructor is scary in itself since they are often and hidden as destructors. Thanks. – bd2357 May 29 '15 at 19:10
2

Insofar as the compiler you're using is even marginally compliant with the standard (I'm looking at you Turbo C++). This is a non-issue because the standard makes strong guarantees about construction and destruction. Those guarantees are the foundation of RAII which is the basis of the "Modern" c++ style.

Mgetz
  • 5,108
  • 2
  • 33
  • 51