On Thursday, 7 June 2018 at 21:07:26 UTC, DigitalDesigns wrote:
class A;
class B
{
A a = new A();
}
auto b1 = new B();
auto b2 = new B();
assert(b1.a == b2.a)!!
I'm glad I finally found this out! This is not typical behavior
in most languages is it?
I'd expect it to be translated to something like
class B
{
A a;
this()
{
a = new A();
}
}
In C# it is different, can't remember if it is different in
C++. This has caused bugs in my code because the fields are all
pointing to the same data when I expected them to each have
unique data ;/
This method is error prone and the behavior should be reversed,
it should not break the majority of code. If one wants the
current behavior then static new could be used or something
else.
The spec looks pretty clear to me on that point
https://dlang.org/spec/class.html#field-init
Besides, defining behaviour at construction is what constructors
are for, I wouldn't expect anything outside a constructor to
happen when an object is constructed. So while I understand that
other languages may (successfully for them) do things differently
I don't think I'd like a breaking change for that.