www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - dynamic array + copy ctor

reply vit <vit vit.vit> writes:
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
next sibling parent reply Stanislav Blinov <stanislav.blinov gmail.com> writes:
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
parent vit <vit vit.vit> writes:
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:
 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
Thanks, That bug is 1.5 years old. Are this problems with copy ctors hard to fix? Are copy ctors still experimental functionality?
Dec 20 2021
prev sibling parent Tejas <notrealemail gmail.com> writes:
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