camino
camino

Reputation: 10584

How to make sure every data members of a class have been copied in its copy constructor?

When a class has many data members, it is hard to figure out whether a data member is copied or not in its copy constructor.

Is there a solution?

Upvotes: 5

Views: 110

Answers (3)

Bathsheba
Bathsheba

Reputation: 234665

The best thing to do is to rely on the compiler generated one, and ensure the class members copy appropriately.

You can do this explicitly using = default: available since c++11.

Upvotes: 3

Cheers and hth. - Alf
Cheers and hth. - Alf

Reputation: 145239

A simple solution is to make sure every member type is copyable, and that there are e.g. no pointers to self or other pointers or references that require fix-ups. Then the generated copy-constructor is good enough.

Upvotes: 8

W.F.
W.F.

Reputation: 13988

If you need to create copy constructor you could use of some helper structure for which you will not create the copy constructor (leave the default one) and store the data that should be copied in the field (by value) of this type. You will then need only the one field to be copied.

Upvotes: 0

Related Questions