禁用复制/分配,为儿童自动禁用?

时间:2015-12-17 17:03:57

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

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

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

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

class Bar : public Foo {
}

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

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

"删除"的行为类似于" 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