Thread overview | ||||||
---|---|---|---|---|---|---|
|
December 22, 2018 Concerns about struct initialization | ||||
---|---|---|---|---|
| ||||
Hello, I have two concerns about struct initialization It would be nice to hear your opinion 1) would like to override default copy initialization code example: import std.stdio; void main(){ struct A{ this(int n) { writeln("construct int"); } this(ref const A other) { writeln("construct ref A"); } ref A opAssign(ref const A other) { writeln("opAssign"); return this; } } A a1 = A(1); A a2 = A(a1); A a3 = 1; A a4; a4 = a1; A a5 = a1; //does not call constructor or opAssign } 2) I was reading this: https://dlang.org/spec/struct.html#dynamic_struct_init It's pretty weird that a static opCall works as a constructor Problems are: - it doesn't work when ANY constructor is defined - it blocks calling to default constructor code example: import std.stdio; struct A{ static A opCall(int n) { writeln("opCall"); A a; return a; } //adding a constructor will error //this(string str) {} } void main(){ A a1 = 1; //calls opCall //calling default constructor will error //A a2 = A(); } |
December 22, 2018 Re: Concerns about struct initialization | ||||
---|---|---|---|---|
| ||||
Posted in reply to Dru | On Saturday, 22 December 2018 at 08:53:20 UTC, Dru wrote: > 1) > would like to override default copy initialization In order to do this, you need to use a postblit (https://dlang.org/spec/struct.html#struct-postblit): ``` struct A { this(this) { writeln("postblit called"); } } void main() { A a; A b = a; // prints "postblit called" } ``` See also DIP1018 (https://github.com/dlang/DIPs/blob/07da1f2cabc8b1bc3ad66034598a133e5ad13356/DIPs/DIP1018.md) which proposes that we switch to regular copy constructors for this. |
December 22, 2018 Re: Concerns about struct initialization | ||||
---|---|---|---|---|
| ||||
Posted in reply to Johannes Loher | Thanks didn't know about postblits =) That DIP looks good, except that they used "ref" instead of "ref const" which would be safer I hope it gets implemented |
December 22, 2018 Re: Concerns about struct initialization | ||||
---|---|---|---|---|
| ||||
Posted in reply to Dru | On Saturday, 22 December 2018 at 11:47:31 UTC, Dru wrote: > Thanks didn't know about postblits =) > > That DIP looks good, except that they used "ref" instead of "ref const" > which would be safer > > I hope it gets implemented DIP1018 is currently in community review. If you have any feedback, please voice it here: https://forum.dlang.org/thread/eoqddfqbjtgfydajozsn@forum.dlang.org |
Copyright © 1999-2021 by the D Language Foundation