Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implement copy-ctor in terms of copy-operator or separately?

This is not a duplicate of Implementing the copy constructor in terms of operator= but is a more specific question. (Or so I like to think.)

Intro

Given a (hypothetical) class like this:

struct FooBar {
  long id;
  double valX;
  double valZ;
  long   valN;
  bool   flag; 
  NonCopyable implementation_detail; // cannot and must not be copied

  // ...
};

we cannot copy this by the default generated functions, because you can neither copy construct nor copy a NonCopyable object. However, this part of the object is an implementation detail we are actually not interested in copying.

It does also does not make any sense to write a swap function for this, because the swap function could just replicate what std::swap does (minus the NonCopyable).

So if we want to copy these objects, we are left with implementing the copy-ctor and copy-operator ourselves. This is trivially done by just assigning the other members.

Question

If we need to implement copy ctor and operator, should we implement the copy ctor in terms of the copy operator, or should we "duplicate" the code with initialization list?

That is, given:

FooBar& operator=(FooBar const& rhs) {
  // no self assignment check necessary
  id = rhs.id;
  valX = rhs.valX;
  valZ = rhs.valZ;
  valN = rhs.valN;
  flag = rhs.flag;
  // don't copy implementation_detail
  return *this;
}

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)
// don't copy implementation_detail
{ }

Possible aspects for an answer would be performance vs. maintainability vs. readability.

like image 206
Martin Ba Avatar asked Feb 25 '23 21:02

Martin Ba


1 Answers

Normally you implement assignment operator in terms of copy constructor (@Roger Pate's version):

FooBar& operator=(FooBar copy) { swap(*this, copy); return *this; }
friend void swap(FooBar &a, FooBar &b) {/*...*/}

This requires providing a swap function which swaps relevant members (all except implementation_detail in your case).

If swap doesn't throw this approach guarantees that object is not left in some inconsistent state (with only part members assigned).

However in your case since neither copy constructor, nor assignment operator can throw implementing copy constructor in terms of assignment operator (a) is also fine and is more maintainable then having almost identical code in both places (b).

like image 141
vitaut Avatar answered Mar 07 '23 01:03

vitaut