digitalmars.D - Concerns about struct initialization
- Dru (51/51) Dec 22 2018 Hello,
- Johannes Loher (16/18) Dec 22 2018 In order to do this, you need to use a postblit
- Dru (5/5) Dec 22 2018 Thanks didn't know about postblits =)
- Johannes Loher (4/9) Dec 22 2018 DIP1018 is currently in community review. If you have any
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(); }
Dec 22 2018
On Saturday, 22 December 2018 at 08:53:20 UTC, Dru wrote:1) would like to override default copy initializationIn 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/07da1f2cabc8b1bc3ad66034598a133e5ad13 56/DIPs/DIP1018.md) which proposes that we switch to regular copy constructors for this.
Dec 22 2018
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
Dec 22 2018
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 implementedDIP1018 is currently in community review. If you have any feedback, please voice it here: https://forum.dlang.org/thread/eoqddfqbjtgfydajozsn forum.dlang.org
Dec 22 2018