我有一个相当大而冗长的类,其中隐式生成的复制构造函数将 几乎 做正确的事情,除了一个特定字段。
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; };更多推荐
隐式副本构造函数在用户定义的副本构造函数中的使用
发布评论