Bug 18706 – Documentation on default class member initializers could be improved

Status
NEW
Severity
enhancement
Priority
P4
Component
dlang.org
Product
D
Version
D2
Platform
Other
OS
Other
Creation time
2018-04-02T14:25:26Z
Last change time
2024-12-15T15:24:59Z
Assigned to
No Owner
Creator
Laurent Tréguier
See also
https://issues.dlang.org/show_bug.cgi?id=2947
Moved to GitHub: dlang.org#4086 →

Comments

Comment #0 by dlang — 2018-04-02T14:25:26Z
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
THIS ISSUE HAS BEEN MOVED TO GITHUB https://github.com/dlang/dlang.org/issues/4086 DO NOT COMMENT HERE ANYMORE, NOBODY WILL SEE IT, THIS ISSUE HAS BEEN MOVED TO GITHUB