Copy Constructor

Ali Çehreli acehreli at yahoo.com
Sun Jun 5 21:39:21 UTC 2022


On 6/5/22 14:04, Alain De Vos wrote:
 > Could it be the copy constructor is only called during assignments (like
 > C++).

The assignment operator is used during assignments both in C++ and D.

A confusion comes from the fact that construction uses the same operator 
as assignment:

   a = b;  // Assignment because 'a' already exists

   auto c = b; // Copy construction because 'c' is being constructed

 > And for one, two there is an explicit assignment.

Actually, both are copy construction:

   Foo one = Foo(1), two = 2;

You will never find me write code like because it's unclear. My version 
would be the following:

   Foo one = Foo(1);
   Foo two = 2;

But even that is not my style because the first line repeats Foo and the 
second line hides the fact that there is construction. So, this is what 
I write in my programs:

   auto one = Foo(1);
   auto two = Foo(2);

 > But not for three where there is a conversion ?

There are two "three"s in that code. The first one is construction (not 
copy):

   [one, two, Foo(3)]

And the other one is copy construction:

   auto three = ++two;

'two' is first incremented and then a copy is made from 'two's new state.

Ali



More information about the Digitalmars-d-learn mailing list