禁用复制/分配,自动为子项禁用
Disable copy/assignment, automatically disabled for children?
使用以下代码禁用复制和分配时:
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
相关文章:
- 强制复制分配超过移动分配运算符
- 使用不兼容的分配器复制分配无序列图
- 复制分配C++相同类型的 lambda
- C++ - 从移动分配运算符调用复制分配
- 不工作 复制分配运算符
- 我的程序运行良好,可以复制对象,但是当我使用复制分配(=)时,它仍然可以正常运行.为什么不给错误
- 复制分配shared_ptr导致分段错误?
- 使用新放置作为复制分配运算符不好吗?
- 未定义 Lambda 复制分配运算符
- 为什么合成的复制分配运算符被定义为如果类有参考成员,则将其定义为删除
- 默认移动分配调用析构函数,复制分配不
- 复制构造函数和复制分配操作员
- 为什么完美的转发(全部捕获)不能实现复制分配?
- C 复制分配运算符,用于参考对象变量
- 复制分配操作员定义
- 编译时,复制构造函数/复制分配和正常功能调用优化之间是否存在任何区别
- C 复制分配操作员问题
- 此对象创建期间发生哪些复制/分配操作
- 矢量未正确擦除内容(复制分配运算符的量运行直到崩溃 [BEX])
- 未在函数中调用复制分配