This is not a duplicate. Implementing the copy constructor from the perspective of the = operator , but this is a more specific question. (Or so I like to think.)
Introduction
Given a (hypothetical) class as follows:
struct FooBar { long id; double valX; double valZ; long valN; bool flag; NonCopyable implementation_detail;
we cannot copy this using the default functions, because you can neither copy the construct nor copy the NonCopyable object. However, this part of the object is an implementation detail that we are not actually interested in copying.
It also makes no sense to write a swap function for this, because the swap function can simply replicate what std :: swap does (minus NonCopyable).
So, if we want to copy these objects, we need to implement instance-ctor and copy-operator. This is trivially done by simply assigning other members.
Question
If we need to implement copy ctor and operator, should we implement a copy of ctor in terms of the copy operator, or should we "duplicate" the code using an initialization list?
That is, given:
FooBar& operator=(FooBar const& rhs) {
Should we write a)
FooBar(FooBar const& rhs) { *this = rhs; }
or b)
FooBar(FooBar const& rhs) : id(rhs.id) , valX(rhs.valX) , valZ(rhs.valZ) , valN(rhs.valN) , flag(rhs.flag)
Possible aspects of the response may be performance versus maintainability and readability.
source share