C++ to D: mutable

Jonathan M Davis jmdavisProg at gmx.com
Fri Mar 25 11:39:40 PDT 2011


> Jonathan M Davis Wrote:
> > > const int a=0;
> > > *cast(int*)&a=1;
> > 
> > There are so many reasons to cringe at that. Taking the address of a
> > local variable is generally very dangerous. As long as the pointer
> > doesn't escape and exist beyond the life the variable, then you're okay,
> > but you often can't guarantee that, and it's generally a _bad_ thing to
> > do.
> 
> `mutable` is a modifier for member fields, I suppose.
> You see the code. If it has bugs, you can find them.

With simple code, it's not hard. But it doesn't take much before you run into 
trouble. For instance, you pass the pointer to another function for it to do 
something. That function may or may not end up causing that pointer to escape. 
And even if it _doesn't_ do that that at first, it could later, and it 
wouldn't be obvious in the code that actually has the local variable. Yes, if 
you're careful, you can avoid problems with escaped pointers, but it's a 
definite risk and generally speaking best avoided. Sometimes it may be 
necessary (especially when calling C code), but it shouldn't be necessary very 
often - especially in pure D code.

> > It breaks the type system. It's
> > also _very_ bad to do in the general case, because the variable in
> > question could actually be immutable underneath rather than just const.
> 
> Can you create an immutable object of a class without immutable
> constructor?

Hmmm. Well, ignoring casting, I don't think so, but there _is_ always casting 
(of course, then the actual object wouldn't really be immutable anyway). Yes, 
if you're careful, you can be sure that a const object is really mutable 
underneath rather than immutable, but it's a definite risk, and you have to be 
aware of a lot more code. So, you _can_ know in specific cases if you're 
careful, but in the general case, you can't know whether a const object is 
really mutable or immutable underneath.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list