What guarantees does D 'const' provide, compared to C++?
Walter Bright
newshound2 at digitalmars.com
Fri Aug 17 13:22:29 PDT 2012
On 8/16/2012 5:51 PM, Torarin wrote:
> The C++ standard, section 7.1.6.1:
>
> 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.
That applies to a "const object", i.e. an object declared as const:
const int x;
It does not apply to a non-const object. If you've got a pointer-to-const, and
it points to a non-const object, you can legitimately cast away the const-ness,
and modify it.
Such is not undefined behavior.
Check 5.2.11.
The crux of the matter is C++'s use of the word "const" to sometimes mean a
storage class and sometimes a type constructor, and it takes some careful
reading of the spec to pick apart the two.
In D, const is always a type constructor, and casting away const and then
modifying the resulting object is undefined behavior, whether or not the
original object was const or mutable.
More information about the Digitalmars-d
mailing list