This is the mail archive of the mailing list for the GCC project.

Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: Missed optimization with const member

On Wed, 2017-07-05 at 12:14 +0100, Jonathan Wakely wrote:
> No, that would be undefined behaviour. The data member is defined as
> const, so it's not possible to write to that member without undefined
> behaviour. A variable defined with a const type is not the same as a
> variable accessed through a pointer/reference to a const type.
> Furthermore, casting the Object to a derived class would also be
> undefined, because the dynamic type is Object, not some derived type.

Ugh, you're right.  Sorry for the misleading examples.

> I think the reason it's not optimized away is for this case:
> void somefunction(const Object& object);
> {
>   void* p = &object;
>   object.~Object();
>   new(p) Object();
> }
> This means that after calling someFunction there could be a different
> object at the same location (with a possibly different value for that
> member).

This is basically what I was trying to say.  The function call acts as
an optimization barrier in this case because it could do anything with
that memory address it gets passed.  If the example is changed to:

void somefunction(const Object& object);

void callInitA(Object& x) {
    Object o;

we can observe that everything of "Object o" gets optimized away as
expected.  And for that, the member doesn't even need to be const.

Is there actually any particular optimization mechanism in GCC that
takes advantage of "const"?  I'm not aware of any such thing.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]