Missed optimization with const member
Oleg Endo
oleg.endo@t-online.de
Wed Jul 5 09:14:00 GMT 2017
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
More information about the Gcc
mailing list