Workarounds for Lack of Mutable Keyword

Craig Black craigblack2 at cox.net
Wed Apr 2 21:54:23 PDT 2008


Part of the uneasiness about D's const is that it is much more strict than 
C++'s, and so has the perception of being more difficult to work with.  For 
example, D lacks C++ mutable keyword, so that there is no way to specify a 
mutable field.  Janice suggested a solution to this that would probably work 
for most purposes:

>There are trivial workarounds. Instead of
>
>    class C
>    {
>        int x;
>        mutable int y;
>    }
>
>    void f(const(C) c);
>
>just do this:
>
>    class C
>    {
>        int x;
>    }
>
>    class D
>    {
>        int y;
>    }
>
>    void f(const(C) c, D d);

Although this may be good for most, this doesn't work for me, because to use 
this approach, I would have to make an extra heap allocation, and use an 
extra parameter.  An extra parameter may not seem like a big deal to some. 
However, a compiler can optimize small recursive functions with small 
numbers of parameters using registers, so there could be a significant 
performance penalty for adding a single parameter to a recursive function.

I have a more hackish solution that won't cost me any performance. I'm 
pretty sure it will work, but I haven't quite fleshed out the details. 
Maybe some of you D template gurus could help me with this one.  My idea is 
to have a ConstAssign template that would subvert const somehow and assign a 
value to const data.  Here's how it would work to replace a mutable field:

class C
{
      int x;
      int y;
      void setY(int ny) { ConstAssign(y, ny); }
}

Since D has pointers and unions, there's probably some ugly hackish trick we 
can employ to subvert const.  The idea is to put this ugly hack in a 
template function.  This would provide a not-so-messy workaround fo the lack 
of mutable that doesn't cost anyperformance or memory.

-Craig 




More information about the Digitalmars-d mailing list