According to the docs (https://dlang.org/spec/class.html#constructors), class members can be initialized with code like this:
------------------------
class MyClass {
int integer = 42;
Object objectMember = new Object();
}
------------------------
At first glance, this seems pretty straightforward, as such syntax can be used in other languages such as Java. However, when the member's type is a class and not a basic type or a struct, things behave differently in D.
A single object will be created and used to initialize `objectMember` in every `MyClass` instance. Every new `MyClass` object will not have its own `Object` instance in `objectMember`, but instead all of them will hold a reference to the same object. Example : https://run.dlang.io/is/Qlx2xY
This behavior can come as unexpected when coming from another language, and expliciting it in the docs might be helpful for newcomers.
Comment #1 by schveiguy — 2018-06-07T21:59:44Z
Issue 2947 is a long-standing bug report on this behavior, so at some point, it might get fixed. But I don't want to close this as a duplicate, because this is specifically about improving the documentation.
Comment #2 by robert.schadek — 2024-12-15T15:24:59Z