www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.bugs - [Issue 18706] New: Documentation on default class member

https://issues.dlang.org/show_bug.cgi?id=18706

          Issue ID: 18706
           Summary: Documentation on default class member initializers
                    could be improved
           Product: D
           Version: D2
          Hardware: Other
                OS: Other
            Status: NEW
          Severity: enhancement
          Priority: P1
         Component: dlang.org
          Assignee: nobody puremagic.com
          Reporter: laurent.treguier.sink gmail.com

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.

--
Apr 02 2018