abelenky abelenky - 3 months ago 17
C++ Question

Use of the Implicit Copy Constructor in User-Defined Copy Constructor

I have a rather large and lengthy class where the implicitly generated copy-constructor would almost do exactly the right thing, except for one specific field.

Is there a way to write a user-defined copy-constructor that calls the implicit version, and then adds one or two lines at the end? Or do I have to write a lengthy, (and boring, and typo-prone) user-defined copy-constructor that mostly duplicates the implicit one?

class MySimpleObject
{
private:
FieldA m_fieldA;
FieldB m_fieldB;
[... repeated a lot...]
SpecialField m_trickyField;

public:
MySimpleObject(const MySimpleObject& other)
{
ImplicitCopyCtor(*this,other); // This is what I want to simplify, instead of copying all the fields by hand.

m_trickyField.DoCloneSeparately(other.m_trickyField);
}
};


Note: SpecialField is provided by a 3rd party library, so I cannot refactor it or modify it. I don't know why it doesn't copy properly, but it doesn't, and I assume there's a good reason. I like the idea of wrapping it inside a class that will behave properly. I'll look into that.

Answer

The fundamental theorem of software engineering is your friend:

struct MakeSpecialSnowflakeLessSpecial
{
  MakeSpecialSnowflakeLessSpecial(const MakeSpecialSnowflakeLessSpecial& other)
  {
    m_trickyField.DoCloneSeparately(other.m_trickyField);
  }

  SpecialField m_trickyField;
};


class MySimpleObject
{
private:
   FieldA m_fieldA;
   FieldB m_fieldB;
   [... repeated a lot...]
   MakeSpecialSnowflakeLessSpecial m_special;

public:
    MySimpleObject(const MySimpleObject&) = default;
};
Comments