Hi,

On Wed, 2017-07-05 at 02:02 +0200, Geza Herman wrote:
> 
> Here's what happens: in callInitA(), an Object put onto the stack (which 
> has a const member variable, initialized to 0). Then somefunction called 
> (which is intentionally not defined). Then ~Object() is called, which 
> has an "if", which has a not-immediately-obvious, but always false 
> condition. Compiling with -03, everything gets inlined.
> 
> My question is about the inlined ~Object(). As m_initType is always 0, 
> why does not optimize the destructor GCC away? GCC inserts code that 
> checks the value of m_initType.
> 
> Is it because such construct is rare in practice? Or is it hard to do an 
> optimization like that?

It's not safe to optimize it away because the compiler does not know
what "somefunction" does.  Theoretically, it could cast the "Object&"
to some subclass and overwrite the const variable.  "const" does not
mean that the memory location is read-only in some way.

For some more explanations about const, see e.g. here 
https://stackoverflow.com/questions/4486326/does-const-just-mean-read-only-or-something-more

You can try showing "somefunction" to the compiler (i.e. put it into
the same translation unit in your example, or build the whole thing
with LTO) and see what happens.

Cheers,
Oleg

Reply via email to