Missed optimization with const member
Oleg Endo
oleg.endo@t-online.de
Wed Jul 5 12:17:00 GMT 2017
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;
    somefunction(x);
}
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.
Cheers,
Oleg
More information about the Gcc
mailing list