This is the mail archive of the
gcc@gcc.gnu.org
mailing list for the GCC project.
const and strict aliasing rules
- From: "John L. Kulp" <jlkjr at bioleap dot com>
- To: gcc at gcc dot gnu dot org
- Date: Mon, 04 Dec 2006 18:27:35 -0500
- Subject: const and strict aliasing rules
I have a situation where I have a class that internally maintains a
container object of non-const objects that it wants to publish to
clients as a const container of const objects, that is, clients can't
modify the list or the items in the list. The data member wants to be
non-const because the managing class needs to create and delete the foo
objects.
data member:
PtrList<foo> listOfFoo;
publishing member functions:
const PtrList<const foo> &GetFooList () const {
return reinterpret_cast<PtrList<const foo>&>(listOfFoo);
}
This results in the warning:
"type punning to incomplete type might break strict aliasing rules"
because the types aren't exactly the same with regard to cv qualifiers.
While I understand the general issue of aliasing incompatible types,
simply adding const qualifiers shouldn't provoke aliasing warnings, as I
believe it is a reasonable thing to want to do, at least in the
direction of adding const. I understand it is probably hard to detect
this in situations like the above. Perhaps there is a need for the
inverse to the const_cast construct, namely, add const rather than
remove it.
You can work around this by using union's of pointers of both non-const
and const types, but the reinterpret_cast solution would be more attractive.
Thoughts?