简体   繁体   English

C ++拷贝构造函数和赋值

[英]C++ copy-constructor and assignment

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? 这样的类仍然可以复制构造吗?

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. 只要您的类提供public拷贝构造函数,您的类就是可复制构造的。

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. 如果你的类需要可分配,那么理想情况下它应该没有const成员。

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. 如果您的类具有const成员,则默认编译器生成的复制赋值运算符将不起作用,因为它尝试分配给不允许的const成员。 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. 如果您的代码意外使用它,编译器将会生成错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM