Unexpected copy constructor behavior
Steven Schveighoffer
schveiguy at gmail.com
Thu Jul 9 22:18:59 UTC 2020
On 7/9/20 6:08 PM, psycha0s wrote:
> import std.stdio;
>
> struct Foo {
> int value;
>
> this(int n)
> {
> value = n;
> writeln("constuctor ", &this);
> }
>
> ~this()
> {
> writeln("destuctor ", &this);
> }
>
> this(ref return scope Foo other)
> {
> value = other.value;
> writeln("copy constuctor ", &this);
> }
> }
>
> void main()
> {
> writeln("begin");
> auto foo1 = Foo(1);
> auto foo2 = foo1;
> writeln("---");
> foo2 = foo1;
> writeln("===");
> writeln("end");
> }
Looking at the generated AST, it's because the compiler is adding an
auto-generated opAssign, which accepts a Foo by value. It is that object
that is being created and destroyed. Your objects aren't moving.
Here is what AST looks like for main:
void main()
{
writeln("begin");
Foo foo1 = foo1 = 0 , foo1.this(1);
try
{
Foo foo2 = foo2 = 0 , foo2.this(foo1);
try
{
writeln("---");
foo2.opAssign(((Foo __copytmp434 = __copytmp434 = 0 ,
__copytmp434.this(foo1);) , __copytmp434));
writeln("===");
writeln("end");
}
finally
foo2.~this();
}
finally
foo1.~this();
return 0;
}
-Steve
More information about the Digitalmars-d-learn
mailing list