隐式副本构造函数在用户定义的副本构造函数中的使用

编程入门 行业动态 更新时间:2024-10-28 20:21:05
本文介绍了隐式副本构造函数在用户定义的副本构造函数中的使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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

更多推荐

隐式副本构造函数在用户定义的副本构造函数中的使用

本文发布于:2023-10-25 03:06:30,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1525739.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:副本   函数   定义   用户   隐式

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!