lazy construction of an immutable object
Ali Çehreli via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Tue Jul 15 06:59:24 PDT 2014
On 07/15/2014 05:20 AM, Puming wrote:
> I found another way to do this, namely first create a class that is
> mutable, then cast it to an immutable object before using it.
>
> ```d
>
> class A {
> int a;
> B b;
> this(int a, int b)
> {
> this.a = a;
> this.b = new B(b);
> }
> }
>
>
> class B {
> int b;
> this(int b)
> {
> this.b = b;
> }
> }
>
> @property immutable(T) freeze(T)(T obj)
> {
> return cast(immutable(T))(obj);
> }
>
> void main()
> {
>
> immutable c = new A(3, 4).freeze;
> c.b.b = 5; // Error: can only initialize const member b inside
> constructor
> writeln(c.b.b)
> }
> ```
>
> But the draw back is that you can't garanteed that the mutable object is
> never used.
Also consider: A pure function's return value can implicitly be
converted to immutable.
class A
{
int x;
int y;
this (int x) pure
{
this. x = x;
}
}
pure A makeA(int x) // <-- returns mutable
{
auto a = new A(x);
// ...
// Set a member later on:
a.y = 42;
return a;
}
void main()
{
immutable imm = makeA(1); // <-- works
}
Ali
More information about the Digitalmars-d-learn
mailing list