www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Initialization of structure field w/o default ctor

reply drug <drug2004 bk.ru> writes:
What's the best way to initialize structure field that has no default ctor?
http://dpaste.dzfl.pl/64cd0a3879fa

Also can I avoid "dummy" non-default ctor for Bar?
Jan 22 2015
parent reply "bearophile" <bearophileHUGS lycos.com> writes:
drug:

 Also can I avoid "dummy" non-default ctor for Bar?
One solution: struct Foo { int foo; disable this(); this(int foo_) pure nothrow safe nogc { this.foo = foo_; } } struct Bar { enum arraySize = 3; Foo[arraySize] foo = Foo(1); } void main() safe { import std.stdio; Bar bar; bar.writeln; } Bye, bearophile
Jan 22 2015
parent reply drug <drug2004 bk.ru> writes:
On 22.01.2015 15:30, bearophile wrote:
 drug:

 Also can I avoid "dummy" non-default ctor for Bar?
One solution: struct Foo { int foo; disable this(); this(int foo_) pure nothrow safe nogc { this.foo = foo_; } } struct Bar { enum arraySize = 3; Foo[arraySize] foo = Foo(1); } void main() safe { import std.stdio; Bar bar; bar.writeln; } Bye, bearophile
Yes, that's what the doctor prescribed. Thank you!
Jan 22 2015
parent "Kenji Hara" <k.hara.pg gmail.com> writes:
On Thursday, 22 January 2015 at 12:45:53 UTC, drug wrote:
 On 22.01.2015 15:30, bearophile wrote:
 drug:

 Also can I avoid "dummy" non-default ctor for Bar?
One solution: struct Foo { int foo; disable this(); this(int foo_) pure nothrow safe nogc { this.foo = foo_; } } struct Bar { enum arraySize = 3; Foo[arraySize] foo = Foo(1); } void main() safe { import std.stdio; Bar bar; bar.writeln; } Bye, bearophile
Yes, that's what the doctor prescribed. Thank you!
Or you can use block assignment in the constructor. struct Bar { enum ArraySize = 3; Foo[ArraySize] foo; this(string dummy) // <== here because compiler demands to initialize field foo { import std.algorithm: fill; //fill(foo[], Foo(0)); foo[] = Foo(0); // <== OK } } Compiler can recognize the block assignment as a construction for the field Bar.foo. Kenji Hara
Jan 22 2015