Thread overview
Initializing a class member that is an object
Mar 30, 2018
Laurent Tréguier
Mar 30, 2018
ketmar
Mar 30, 2018
ketmar
Mar 30, 2018
Laurent Tréguier
Mar 30, 2018
ketmar
Mar 30, 2018
Laurent Tréguier
March 30, 2018
Coming from a more Java-esque background, I'm used to sometimes initializing class members outside of the constructor :

class MyClass {
    Object member = new Object();
}

I've tried using this in D, but I've come to realize it acts very differently. In Java, the `new Object()` will be executed every time a new `MyClass` object is instantiated. In D however, it seems to be executed once, and members of every `MyClass` object will then be initialized with a reference to that one unique `Object`.

Example: https://run.dlang.io/is/Qlx2xY

Is this behavior really intentional ? I don't really see how it could be useful, and it's really confusing at first to see new objects with weird values even if none of their members has been touched yet...
March 30, 2018
Laurent Tréguier wrote:

> Is this behavior really intentional ?
yes. default values should be the same for all objects. it is predictable, and allows to initialize objects to the known state simply by blitting `.init`.

that is, default values aren't a syntax sugar for defining implicit ctor actions, they are executed once. this is by design.
March 30, 2018
p.s.: still, it may be nice to warn user about that. 'cause such runtime initializations are really belong to static ctor. dunno, i'm ok both with warning and without it.
March 30, 2018
On Friday, 30 March 2018 at 11:04:59 UTC, ketmar wrote:
> p.s.: still, it may be nice to warn user about that. 'cause such runtime initializations are really belong to static ctor. dunno, i'm ok both with warning and without it.

I simply think a word about it in the docs would be nice, since this is tricky if you come from another language that doesn't do this. Otherwise I'm fine with it (and it's not exactly hard to fix either)
March 30, 2018
Laurent Tréguier wrote:

> On Friday, 30 March 2018 at 11:04:59 UTC, ketmar wrote:
>> p.s.: still, it may be nice to warn user about that. 'cause such runtime initializations are really belong to static ctor. dunno, i'm ok both with warning and without it.
>
> I simply think a word about it in the docs would be nice, since this is tricky if you come from another language that doesn't do this. Otherwise I'm fine with it (and it's not exactly hard to fix either)

please, make an ER in bugzilla then. 'cause it will be lost here, and with ER we have a chance to eventually do that.
March 30, 2018
On Friday, 30 March 2018 at 11:14:32 UTC, ketmar wrote:
> please, make an ER in bugzilla then. 'cause it will be lost here, and with ER we have a chance to eventually do that.

Will do.