mutable keyword

Namespace via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri May 20 10:28:55 PDT 2016


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;
	}
	
	void change() const
	{
		(*_id)++;
	}
}

void main() {
	import std.stdio;
	
	A a = A(42);
	a.change();
	
	writeln(a.id);
}
----


More information about the Digitalmars-d-learn mailing list