隐式副本构造函数在用户定义的副本构造函数中的使用 [英] Use of the Implicit Copy Constructor in User-Defined Copy Constructor

查看:121
本文介绍了隐式副本构造函数在用户定义的副本构造函数中的使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个相当大而冗长的类,其中隐式生成的复制构造函数将 几乎 做正确的事情,除了一个特定字段。

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);
    }
};

注意: SpecialField由第三方库提供,所以我不能重构或修改它。我不知道为什么为什么无法正确复制,但是不能正确复制,我认为这是有充分理由的。我喜欢将其包装在可以正常运行的类中的想法。我会调查的。

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.

推荐答案

软件工程的基本定理是您的朋友:

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;
};

这篇关于隐式副本构造函数在用户定义的副本构造函数中的使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆