Unexpected copy constructor behavior

psycha0s box at mail.com
Thu Jul 9 22:08:18 UTC 2020


I was learning copy constructors and got a really weird result. 
It looks like a copy constructor and a destuctor of two unknown 
objects are called. Could somebody please explain it to me?

>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");
>}

The output:

>begin
>constuctor A3D3EFF860
>copy constuctor A3D3EFF864
>---
>copy constuctor A3D3EFF880     // <--
>destuctor A3D3EFF808           // <--
>===
>end
>destuctor A3D3EFF864
>destuctor A3D3EFF860



More information about the Digitalmars-d-learn mailing list