禁用copy/assignment,对儿童自动禁用?
Disable copy/assignment, automatically disabled for children?
使用以下代码禁用复制和赋值时:
Foo(const Foo&) = delete;
Foo& operator=(const Foo&) = delete;
这是否也会自动禁用 Foo 的子 类 的复制和赋值?
class Bar : public Foo {
}
或者说,Bar
可以复制吗?
是的,这也禁止隐式复制 child classes。事实上,这就是从 boost::noncopyable
(http://www.boost.org/doc/libs/master/libs/core/doc/html/core/noncopyable.html) 继承的方式。然而,有人总是可以为 child class 编写自己的副本 constructor/copy 作业,但实际上并没有复制 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
}
同样,当您尝试继承此 class 时,派生的 class 将继承不可复制的特性,如下所示
// 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
使用以下代码禁用复制和赋值时:
Foo(const Foo&) = delete;
Foo& operator=(const Foo&) = delete;
这是否也会自动禁用 Foo 的子 类 的复制和赋值?
class Bar : public Foo {
}
或者说,Bar
可以复制吗?
是的,这也禁止隐式复制 child classes。事实上,这就是从 boost::noncopyable
(http://www.boost.org/doc/libs/master/libs/core/doc/html/core/noncopyable.html) 继承的方式。然而,有人总是可以为 child class 编写自己的副本 constructor/copy 作业,但实际上并没有复制 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
}
同样,当您尝试继承此 class 时,派生的 class 将继承不可复制的特性,如下所示
// 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