This is the mail archive of the
gcc-bugs@gcc.gnu.org
mailing list for the GCC project.
[Bug tree-optimization/80794] constant objects can be assumed to be immutable
- From: "msebor at gcc dot gnu.org" <gcc-bugzilla at gcc dot gnu dot org>
- To: gcc-bugs at gcc dot gnu dot org
- Date: Wed, 17 May 2017 15:40:29 +0000
- Subject: [Bug tree-optimization/80794] constant objects can be assumed to be immutable
- Auto-submitted: auto-generated
- References: <bug-80794-4@http.gcc.gnu.org/bugzilla/>
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=80794
Martin Sebor <msebor at gcc dot gnu.org> changed:
What |Removed |Added
----------------------------------------------------------------------------
Status|WAITING |UNCONFIRMED
Ever confirmed|1 |0
--- Comment #2 from Martin Sebor <msebor at gcc dot gnu.org> ---
Yes, it does. In [basic.type.qualifier], starting with 2014, C++ defines the
term /const object/ like so:
A const object is an object of type const T or a non-mutable subobject of
such an object.
In [dcl.type.cv], C++ then says that:
Except that any class member declared mutable (7.1.1) can be modified, any
attempt to modify a const object during its lifetime (3.8) results in undefined
behavior.
and gives an example similar to yours:
struct X {
mutable int i;
int j;
};
struct Y {
X x;
Y();
};
const Y y;
*p = const_cast<Y*>(&y); // cast away const-ness of y
p->x.i = 99; // well-formed: mutable member can be modified
p->x.j = 99; // undefined: modifies a const member
This example goes back to the original C++ 98 (as does the undefined behavior).
It's slightly different than the example I gave because here the complete
object is declared const, not the member. But the rule is the same either way
(and doesn't change even if the const object is dynamically allocated, say via
'const Y &y = *new const Y();' as a prior example illustrates.)
C has a similar constraint in 6.7.3, p6:
If an attempt is made to modify an object defined with a const-qualified type
through use of an lvalue with non-const-qualified type, the behavior is
undefined.
(But as I said, I think the C constraint is less interesting.)