Copy Constructor

Salih Dincer salihdb at hotmail.com
Sun Jun 5 15:45:17 UTC 2022


Hi,

Let be the structure Foo that wraps an int pointer. Let's setup 
Foo in 3 different ways:
> 1. Foo one = Foo(1);
> 2. Foo two = 2;
> 3. [ Foo(3) ];

Pretty clean, right?

So why it's not run copy-constructor in 3? Also, when we write to 
the screen with writeln(), why four times copy-constructors are 
running?

**Playground:** https://run.dlang.io/is/qHvLJe
**Source:**
```d
struct Foo {
   int payload;

   this(int i)
   {
     this.payload = i;
   }

   this(ref return scope Foo that)
   {
     this = that; //cC = copyConstructor
     logger ~= format("cC(%s)", that.payload);
   }

   Foo opUnary(string op)()
   if(op == "++") {
     ++this.payload;
     return this;
   }

   int getter()
   {
     return payload;
   }
   alias getter this;
}

import std.stdio, std.format;
string logger;

void main() {
   Foo one = Foo(1), two = 2;
   int[] arr = [one, two, Foo(3)];

   auto three = ++two;/*
   two.writeln(": 0x", &two.payload);//*/

   //arr.writeln;/*
   foreach(ref i; arr) {
     i.writeln(": 0x", &i);
   }//*/

   writeln("0x", &three.payload);

   logger.writeln;
} // end with the logger!
/*
Print Outs:
=================
1: 0x7FD13D561000
2: 0x7FD13D561004
3: 0x7FD13D561008
0x7FFE6757E908
cC(1)cC(2)cC(3)
*/
```

SDB at 79


More information about the Digitalmars-d-learn mailing list