On Friday, 20 May 2016 at 18:42:44 UTC, Ali Çehreli wrote:
On 05/20/2016 10:28 AM, Namespace wrote:
> On Thursday, 19 May 2016 at 23:21:14 UTC, Jonathan M Davis
wrote:
>> On Thursday, May 19, 2016 20:44:54 ciechowoj via
Digitalmars-d-learn
>> wrote:
>>> Is there D equivalent of C++'s mutable keyword? Like the
one that
>>> allows to modify a field of struct from constant method. Or
some
>>> alternative solution?
>>
>> No. D's const and immutable provide no backdoors.
>
> But you can cheat:
> ----
> int* _id;
>
> struct A
> {
> int id = 0;
>
> this(int id)
> {
> this.id = id;
> _id = &this.id;
Point taken but considering that D structs are freely movable
value types, I don't think that's a valid D program. The spec
does ban self-referencing structs but I think it also bans the
code above in spirit. :)
> }
>
> void change() const
> {
> (*_id)++;
> }
> }
>
> void main() {
> import std.stdio;
>
> A a = A(42);
> a.change();
>
> writeln(a.id);
> }
> ----
Ali
Also works for classes. ;) It's valid as far as I can tell.