定义复制构造函数时是否总是必须定义复制赋值运算符?

发布于 2024-12-27 10:06:42 字数 290 浏览 3 评论 0原文

我已经多次在脑海中反复思考,如果提供了复制构造函数,则还必须提供赋值运算符。但是,有时类可以使用复制构造函数,但不能使用赋值运算符。

例如:

class A {
public:
  const int myVar;

  A(const int var) : myVar(var) {};
  A(const A& other) : myVar(other.myVar) {};
};

那么这是一件可怕的事情吗?赋值运算符是否需要定义但设为私有?这样的类仍然可以复制构造吗?

I've had it drilled into my head many many times that if a copy-constructor is provided, an assignment operator must also be provided. However, there are times when a class can use a copy-constructor but not an assignment operator.

For example:

class A {
public:
  const int myVar;

  A(const int var) : myVar(var) {};
  A(const A& other) : myVar(other.myVar) {};
};

So is this a terrible thing to do? Does the assignment operator need to be defined but made private? Is such a class still copy-constructable?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

菩提树下叶撕阳。 2025-01-03 10:06:42

那么这是一件可怕的事情吗?
不,事实并非如此。
并非所有类都需要可复制构造和可赋值。拥有可复制构造但不可分配的类是完全有效的。

这样的类仍然可以复制构造吗?
是的,确实如此。
只要您的类提供了 public 复制构造函数,您的类就是可复制构造的。

赋值运算符是否需要定义但设为私有?
这取决于您的使用情况。
如果您的类需要可分配,那么理想情况下它应该没有 const 成员。

如果您的类具有 const 成员,则默认编译器生成的复制赋值运算符将不起作用,因为它尝试分配给不允许的 const 成员。因此,如果您的代码需要复制赋值运算符,您将必须提供自己的重载版本。但是,无论如何,这个重载版本无法提供预期的赋值语义。

如果您的类对象不需要是可分配的,那么就不要定义它。如果您的代码不小心使用了它,编译器无论如何都会生成错误。

So is this a terrible thing to do?
No, it is not.
Not all classes need to be copy constructible as well as assignable. It is perfectly valid to have copy constructible yet non assignable classes.

Is such a class still copy-constructable?
Yes it is.
As long as your class provides a public copy constructor, Your class is copy constructible.

Does the assignment operator need to be defined but made private?
It depends on your usage.
If your class needs to be assignable then it should ideally not have a const member.

The default compiler generated copy assignment operator will not work if your class has an const member because it tries to assign to a const member which is not allowed. So if your code needs a copy assignment operator you will have to provide your own overloaded version. But, Anyway this overloaded version cannot provide expected assignment semantics.

If your class objects do not need to be Assignable then do not define it. If your code does accidentally uses it the compiler will generate an error anyways.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文