digitalmars.D.learn - dynamic array + copy ctor
- vit (37/37) Dec 19 2021 Hello,
- Stanislav Blinov (4/6) Dec 19 2021 Because D runtime isn't properly married to copy constructors
- vit (6/12) Dec 20 2021 Thanks,
- Tejas (40/77) Dec 19 2021 Yeah, Stanislov is right, it's using a blit rather than a copy
Hello, Why is copy ctor in this example not called? ```d import std.stdio; struct Foo { int i; this(int i){ this.i = i; writeln("init: ", i); } this(ref typeof(this) rhs){ this.i = rhs.i; writeln("copy: ", i); } ~this() { writeln("~dtor:", i); } } void main(){ Foo[] foos; foos ~= Foo(1); while(foos.capacity > foos.length) foos ~= Foo(0); foos ~= Foo(2); import core.memory; GC.collect(); } ``` result: ``` init: 1 init: 2 ~dtor:1 ~dtor:2 ~dtor:1 ``` First Foo is destructed 2x.
Dec 19 2021
On Sunday, 19 December 2021 at 22:29:21 UTC, vit wrote:Hello, Why is copy ctor in this example not called?Because D runtime isn't properly married to copy constructors yet. I.e. it's a bug, a variant of this one: https://issues.dlang.org/show_bug.cgi?id=20879
Dec 19 2021
On Sunday, 19 December 2021 at 23:21:00 UTC, Stanislav Blinov wrote:On Sunday, 19 December 2021 at 22:29:21 UTC, vit wrote:Thanks, That bug is 1.5 years old. Are this problems with copy ctors hard to fix? Are copy ctors still experimental functionality?Hello, Why is copy ctor in this example not called?Because D runtime isn't properly married to copy constructors yet. I.e. it's a bug, a variant of this one: https://issues.dlang.org/show_bug.cgi?id=20879
Dec 20 2021
On Sunday, 19 December 2021 at 22:29:21 UTC, vit wrote:Hello, Why is copy ctor in this example not called? ```d import std.stdio; struct Foo { int i; this(int i){ this.i = i; writeln("init: ", i); } this(ref typeof(this) rhs){ this.i = rhs.i; writeln("copy: ", i); } ~this() { writeln("~dtor:", i); } } void main(){ Foo[] foos; foos ~= Foo(1); while(foos.capacity > foos.length) foos ~= Foo(0); foos ~= Foo(2); import core.memory; GC.collect(); } ``` result: ``` init: 1 init: 2 ~dtor:1 ~dtor:2 ~dtor:1 ``` First Foo is destructed 2x.Yeah, Stanislov is right, it's using a blit rather than a copy constructor: ```d import std.stdio; struct Foo { int i; this(this){ writeln("blit: ", i); } this(int i){ this.i = i; writeln("init: ", i); } this(scope ref Foo rhs){ this.i = rhs.i; writeln("copy: ", i); } ~this() { writeln("~dtor:", i); writeln("~dtor:", &this); } } void main() { Foo[] foos ; foos ~= Foo(1); foos ~= Foo(2); } /+ Output: init: 1 init: 2 blit: 1 ~dtor:1 ~dtor:7EFE0DCD3000 ~dtor:2 ~dtor:7EFE0DCD4004 ~dtor:1 ~dtor:7EFE0DCD4000 +/ ```
Dec 19 2021