【问题标题】:Disable copy/assignment, automatically disabled for children?禁用复制/分配,自动为孩子禁用?
【发布时间】:2016-03-24 06:10:26
【问题描述】:

当使用以下代码禁用复制和赋值时:

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

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

class Bar : public Foo {
}

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

【问题讨论】:

  • 不,Bar 无法复制。
  • Bar 的其中一个组件不可复制时,如何复制它?
  • 感谢您的回答!如果您将其放入答案中,我可以接受:)
  • 自动禁用Foo子类的默认复制和分配。它不会阻止编写Foo 子类的人编写自己的复制构造函数和/或赋值运算符。

标签: c++ c++11 copy-constructor assignment-operator


【解决方案1】:

“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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-07
      • 1970-01-01
      相关资源
      最近更新 更多