lazy construction of an immutable object
Meta via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Tue Jul 15 10:09:03 PDT 2014
On Tuesday, 15 July 2014 at 15:48:10 UTC, Puming wrote:
> wow, that's interesting :-) Is it the idiomatic approach to
> initiate immutable objects lazily? Or do people use data class
> with immutable fields and generate a companion builder class at
> compile time?
There's no real idiomatic approach, I think, because this is
somewhat unexplored territory. I'd say constructing the object
inside a pure method so it can be implicitly cast to immutable is
more typesafe, but if you're storing the immutable reference to
the object in a class or struct, it can only be initialized in
that class's/struct's constructor. So the following isn't
possible:
struct Test
{
immutable(int*) n;
private int* getPtr() pure
{
int* n = new int;
*n = 42;
return n;
}
public void initialize() pure
{
n = getPtr();
}
}
void main()
{
auto t = new Test();
test.initialize();
}
More information about the Digitalmars-d-learn
mailing list