www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Re: Transitive const sucks

reply Mike Capp <mike.capp gmail.com> writes:
James Dennett Wrote:

 Well, in C++ you'd be fine, but in D I thought the behavior
 if you modified something after casting away const was
 undefined, so you're out of luck.  (Not that you'd need
 to cast away const for this in C++.)

You'll hit undefined behavior in C++ as well if the data being modified (via a const_cast) was originally declared as const. Compilers can (and some PPC compilers did) put such data in read-only memory, and even if they don't they tend to assume "really, truly const" and optimize accordingly. Hours of fun for all the family. cheers Mike
Sep 13 2007
parent James Dennett <jdennett acm.org> writes:
Mike Capp wrote:
 James Dennett Wrote:
 
 Well, in C++ you'd be fine, but in D I thought the behavior
 if you modified something after casting away const was
 undefined, so you're out of luck.  (Not that you'd need
 to cast away const for this in C++.)

You'll hit undefined behavior in C++ as well if the data being modified (via a const_cast) was originally declared as const.

Something of a mantra around here! However, that's certainly not the case we are talking about. We're talking about situations where an object (which is not changing) has a reference to another (mutable) object and should be able to change that object.
 Compilers can (and some PPC compilers did) put
 such data in read-only memory, and even if they don't they
 tend to assume "really, truly const" and optimize accordingly.

Indeed. Non-mutable parts of objects defined as const in C++ cannot be modified by any well-defined code, and optimizers can and do use that fact to good effect. It's just not what this (sub-)thread was about. -- James
Sep 13 2007