This is the mail archive of the
mailing list for the GCC project.
Re: Missed optimization with const member
- From: Oleg Endo <oleg dot endo at t-online dot de>
- To: Geza Herman <geza dot herman at gmail dot com>, gcc at gcc dot gnu dot org
- Date: Wed, 05 Jul 2017 18:13:51 +0900
- Subject: Re: Missed optimization with const member
- Authentication-results: sourceware.org; auth=none
- References: <email@example.com>
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
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.