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
+/
```