C++没有复制构造函数的赋值运算符
问题:我可以定义赋值运算符而不是复制构造函数吗?对于内部类(未在 API 中公开),这仍然是一个糟糕的设计实践吗?
我需要它的原因:正如这个问题提到的,QObject
将其复制构造函数和赋值运算符设为私有,以便如果子类尝试使用其中任何一个,则会在编译时发出错误。
然而,我需要定义一个赋值运算符,以便复制“值”(而不是“身份”) Qobject
文档 描述了。我不在任何地方使用此类的复制构造函数。
我这样做的原因是不想写复制构造函数的缺点是它将复制我无论如何都不会使用的代码。
The question: Can I define an assignment operator and not the copy constructor? For an internal class (not exposed in the API), is this still a bad design practice?
The reason I need it: As this question mentions, QObject
makes its copy constructor and assignment operator private so that if a subclass tries to use either, an error is issued at compile-time.
I need to define an assignment operator however in order to copy the "value" (and not the "identity" as the Qobject
documentation describes. I don't use this class's copy constructor anywhere.
The reason I don't want to write a copy constructor is that it will be duplicating code that I won't use anyway.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
没有什么可以阻止你。然而,这是一个非常愚蠢的想法。
将
第一个转换为第二个非常简单,但你只是在浪费我的时间,无论是开发人员还是处理器,让我这样做。如果它不是默认可构造的,我想这会更难......但我仍然没有明白这一点。如果复制构造函数很简单,则可以由编译器定义它,或者如果您想要 DRY,您甚至可以根据赋值运算符来定义它。
没有复制构造函数也会抑制复制和交换的能力,这是实现赋值运算符的常用习惯用法。
There's nothing stopping you. It is, however, a pretty dumb idea.
versus
Pretty trivial to transform the first into the second, but you're just wasting my time, both dev and processor, making me do it. If it's not default-constructible, I guess that it would be harder... but I'm still not seeing the point. The copy constructor can be defined by the compiler if it's trivial, or you can even define it in terms of the assignment operator if you want DRY.
Not having a copy constructor will also inhibit your ability to copy-and-swap, the usual idiom for implementing assignment operators.
正如 DeadMG 所说,虽然有可能,但这是相当愚蠢的。
您不必从自己的基类的复制构造函数中调用,因此如果您绝对必须具有值语义,那么它仍然是可能的。但在 QObject 的上下文中,这仍然相当不正统。即使对于您自己的内部类,仍然需要牢记最小惊喜原则。
如果绝对必要,我将避免使用传统的复制构造函数/赋值运算符,并通过成员函数进行工作。
QObject
派生类的预期语义将得到保留,但您有办法明确地执行您想要执行的操作。While possible, as DeadMG says, it is rather foolish.
You don't have to call the base class's copy constructor from your own, so if you absolutely have to have value semantics, then it is still possible. But in the context of
QObject
s, this is still rather unorthodox. Even for your own internal classes, the principle of least surprise still needs to be kept in mind.If absolutely necessary, I would avoid the traditional copy constructor/assignment operator, and work via member functions. The expected semantics of
QObject
derivatives will be maintained, but you have a way to explicitely do what you want to have done.