Meaning of = delete after function declaration
1 2 3 4 5 6 | class my_class { ... my_class(my_class const &) = delete; ... }; |
在这种情况下,
是否有其他"修饰语"(除
删除一个函数是C++ 11的特性:
The common idiom of"prohibiting copying" can now be expressed
directly:
1
2
3
4
5 class X {
// ...
X& operator=(const X&) = delete; // Disallow copying
X(const X&) = delete;
};[...]
The"delete" mechanism can be used for any function. For example, we
can eliminate an undesired conversion like this:
1
2
3
4
5
6 struct Z {
// ...
Z(long long); // can initialize with an long long
Z(long) = delete; // but not anything less
};
这篇摘自C++编程语言[第四版]的Bjarne Stroustrup书讲述了使用EDOCX1的3个方面的真正目的:
Using the default copy or move for a class in a hierarchy is typically
a disaster: given only a pointer to a base, we simply don’t know what
members the derived class has (§3.2.2), so we can’t know how to copy
them. So, the best thing to do is usually to delete the default copy
and move operations, that is, to eliminate the default definitions of
those two operations:
1
2
3
4
5
6
7
8
9
10 class Shape {
public:
Shape(const Shape&) =delete; // no copy operations
Shape& operator=(const Shape&) =delete;
Shape(Shape&&) =delete; // no move operations
Shape& operator=(Shape&&) =delete;
?Shape();
// ...
};Now an attempt to copy a Shape will be caught by the compiler.
The
=delete mechanism is general, that is, it can be used to suppress any operation
Are there any other"modifiers" (other than
= 0 and= delete )?
由于似乎没有其他人回答这个问题,我应该提到还有一个
https://docs.microsoft.com/en-us/cpp/cpp/显式默认和删除的函数显式默认函数
EDCOX1 1是C++ 11中的一个特性。根据
详细地说。
假设在课堂上。
1 2 3 4 5 6 7 8 | Class ABC{ Int d; Public: ABC& operator= (const ABC& obj) =delete { } }; |
调用此函数进行obj赋值时,将不允许这样做。表示赋值运算符将限制从一个对象复制到另一个对象。
我所使用的编码标准对于大多数类声明都有以下内容。
1 2 3 4 5 6 7 | // coding standard: disallow when not used T(void) = delete; // default ctor (1) ~T(void) = delete; // default dtor (2) T(const T&) = delete; // copy ctor (3) T(const T&&) = delete; // move ctor (4) T& operator= (const T&) = delete; // copy assignment (5) T& operator= (const T&&) = delete; // move assignment (6) |
如果您使用这6个选项中的任何一个,您只需注释掉相应的行。
示例:类fizzbus只需要dtor,因此不使用其他5个。
1 2 3 4 5 6 7 | // coding standard: disallow when not used FizzBuzz(void) = delete; // default ctor (1) // ~FizzBuzz(void); // dtor (2) FizzBuzz(const FizzBuzz&) = delete; // copy ctor (3) FizzBuzz& operator= (const FizzBuzz&) = delete; // copy assig (4) FizzBuzz(const FizzBuzz&&) = delete; // move ctor (5) FizzBuzz& operator= (const FizzBuzz&&) = delete; // move assign (6) |
我们只在这里注释1,并在其他地方(可能是编码标准建议的地方)安装它的实现。其他5个(共6个)不允许删除。
您还可以使用"=delete"来禁止对不同大小的值进行隐式升级…例子
1 2 3 4 5 | // disallow implicit promotions template <class T> operator T(void) = delete; template <class T> Vuint64& operator= (const T) = delete; template <class T> Vuint64& operator|= (const T) = delete; template <class T> Vuint64& operator&= (const T) = delete; |
新的C++0X标准。请参见N3242工作草案第8.4.3节。
这是C++0X标准中新的东西,可以删除继承的函数。