Workarounds for Lack of Mutable Keyword

Robert Fraser fraserofthenight at gmail.com
Wed Apr 2 22:50:40 PDT 2008


Craig Black wrote:
> I did it and it was very easy.  I didn't know you could cast away const 
> so easily in D.  This works for const, but not invariant.  Since we have 
> the ability to subvert const so easily, there should be no problem 
> living without mutable fields.
> 
> import std.stdio;
> 
> void ConstAssign(T)(ref const T x, T y) { *cast(T*)&x = y; }
> 
> class A
> {
> public:
>  int x;
>  int y;
>  void setY(int ny) const { ConstAssign(y, ny); }
> }
> 
> void foo(const A a) { a.setY(2); }
> 
> int main(char[][] args)
> {
>  A a = new A;
>  a.y = 1;
>  foo(a);
>  writefln(a.y);
>  return 0;
> }

ight, but be sure to synchronize for multi threaded access.



More information about the Digitalmars-d mailing list