C++ to D: mutable
Jonathan M Davis
jmdavisProg at gmx.com
Thu Mar 24 08:56:07 PDT 2011
> Caligo Wrote:
> > Greetings,
> >
> > I have a C++ class that I would like to rewrite it in D. The class
> > has members that are declared as 'mutable'. How do I achieve the same
> > effect in D? if not, what is recommended?
>
> 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. Also, casting away
const is technically implementation-dependent. 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. And if you then
try and alter that variable, there's a decent chance that it'll segfault or
just plain mess up your program. It might work here, but then again, it might
not. It _probably_ will, but I wouldn't bet on it. And casting away const to
try and have a mutable member variable is just asking for it, unless you can
make a number of guarantees about the object in question - including that it's
_never_ actually immutable. You should check out the stackoverflow post that I
pointed out in a previous post in this thread.
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list