禁用复制/分配,自动为子项禁用

Disable copy/assignment, automatically disabled for children?

本文关键字:复制 分配      更新时间:2023-10-16

使用以下代码禁用复制和分配时:

Foo(const Foo&) = delete;
Foo& operator=(const Foo&) = delete;

这也会自动禁用Foo子类的复制和分配吗?

class Bar : public Foo {
}

或者,换句话说,Bar可以被复制吗?

是的,这也禁止隐式复制子类。事实上,继承boost::noncopyable就是这样(http://www.boost.org/doc/libs/master/libs/core/doc/html/core/noncopyable.html)工作。然而,有些人总是可以为实际上没有复制Foo组件的子类编写自己的复制构造函数/复制赋值,或者以不同的方式复制它。

"delete"的行为类似于"boost::noncopyable"。在c++11中,编译器为您完成任务。

// Example program
#include <iostream>
#include <string>
class Car {
public:
  Car(const Car&) = delete;
  void operator=(const Car&) = delete;
  Car(): owner(0) {}
  void setOwner() { owner = 0; }
private:
 int owner;
};
int main()
{
  Car c1,c3;
  Car c2=c1;//error
  c3=c1;//error 
}

类似地,当您尝试继承这个类时,派生类将继承不可复制的特性,如下所示

// Example program
#include <iostream>
#include <string>
class Car {
public:
  Car(const Car&) = delete;
  void operator=(const Car&) = delete;
  Car(): owner(0) {}
  void setOwner() { owner = 0; }
private:
 int owner;
};
class myCar:public Car{};
int main()
{
  myCar c1,c3;
  myCar c2=c1;//Error
  c3=c1;//Error
}

以下错误:

 In function 'int main()':
19:12: error: use of deleted function 'myCar::myCar(const myCar&)'
15:7: note: 'myCar::myCar(const myCar&)' is implicitly deleted because the default definition would be ill-formed:
15:7: error: use of deleted function 'Car::Car(const Car&)'
7:3: note: declared here