Workarounds for Lack of Mutable Keyword
Craig Black
craigblack2 at cox.net
Wed Apr 2 23:16:37 PDT 2008
"Robert Fraser" <fraserofthenight at gmail.com> wrote in message
news:ft1r7d$1q0b$1 at digitalmars.com...
> 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.
In the case that I'm thinking of using this for, I know multiple threads
won't be contending for the "mutable" fields.
-Craig
More information about the Digitalmars-d
mailing list