Clearly the constructor (or at least the initializer list if not the body of the ctor) needs to be able to write a value to i
.
As it happens, the way C++ achieves this is to make this
a pointer-to-non-const in the constructor (and destructor). Basically, the const
-ness of obj
doesn't commence until the constructor has finished executing. That's why the vulnerability exists, because of a straightforward but imperfect solution to the technical problem of how to construct const
-qualified objects.
Perhaps it could in principle be done differently. I suppose you'd need a separate const
version of the constructor in which the compiler applies different rules (just as normal member functions can be const
), treating data members as const
and therefore (1) allowing them to be initialized but not assigned, (2) forbidding the initialization of ptr
from &i
since the latter would have type int const*
. C++ doesn't do this, and as a result it has this loophole that you've driven through. If it did do it, people would have more difficulty writing constructors in certain cases, so it's a design trade-off.
Be aware that similarly a volatile
-qualified object is not volatile
in its own constructor or destructor.