Bug 4086 – Standard struct constructor for the heap

Status
RESOLVED
Resolution
WORKSFORME
Severity
enhancement
Priority
P2
Component
dmd
Product
D
Version
D2
Platform
All
OS
All
Creation time
2010-04-12T23:56:41Z
Last change time
2018-05-17T12:23:19Z
Assigned to
No Owner
Creator
bearophile_hugs

Comments

Comment #0 by bearophile_hugs — 2010-04-12T23:56:41Z
D allows to initialize a struct on the stack with a default syntax: struct Node { int data; Node* next; } void main() { Node n1 = Node(10); // OK Node n2 = Node(10, null); // OK } So I propose to introduce that same handy automatic syntax for heap allocation too: struct Node { int data; Node* next; } void main() { Node* n1 = new Node(10); // OK Node* n2 = new Node(10, null); // OK } This feature doesn't increase the complexity of the language for the programmer, it lowers the complexity because there is one less special case to remember (even if the compiler can become a bit more complex). To keep things tidy, such default costructor must be absent if any other costructor is defined in the struct: struct Foo { int data; Foo* next; this(int d, Foo* p) { data = d; next = p; } } void main() { Foo* f = new Foo(10); // Error, standard constructor is absent }
Comment #1 by dmitry.olsh — 2018-05-17T12:23:19Z
I thought it always worked like that. So fixed a long time ago.