This question already has an answer here:
c++ syntax: default and delete modifiers
(1个答案)
7年前关闭。
今天早些时候,我问a question导致了另一个问题:我什么时候应该使用
如果还有更多要说的话或我误会了,请发表评论或回答。
当模板函数不能以某种类型运行时,它也很有用:
...您明白了。希望这对某人有帮助!
编辑:
正如注释中正确指出的那样,现在无法删除
(1个答案)
7年前关闭。
今天早些时候,我问a question导致了另一个问题:我什么时候应该使用
=delete
?我认为没有专门针对SO上=delete
的帖子,因此我在一本名为“C++编程语言”的书中进行了查找。我将在下面的答案中列出我的发现。如果还有更多要说的话或我误会了,请发表评论或回答。
最佳答案
原来=delete
非常有用!这里有一些例子:
基本上,我们可以防止复制基类,因为它可能经常导致切片:
struct Base {
Base(){}
Base& operator=(const Base&) = delete; // disallow copying
Base(const Base&) = delete;
Base& operator=(Base && ) = delete; // disallow moving
Base(Base && ) = delete;
};
struct Der : public Base {};
void func() {
Der d;
Base base = d; // this won't work because the copy constructor is deleted!
// this behavior is desired - otherwise slicing would occur
}
当模板函数不能以某种类型运行时,它也很有用:
template<class T>
void fn(T p) { /* ... */ }; // do something with T
void fn(int) = delete; // disallow use with int
void fun() {
fn(4); // aha! cannot use fn() with int!
fn(-4.5); // fine
fn("hello");// fine
}
=delete
也可以禁止不希望的转换:struct Z {
Z(double); // can initialize with a double
Z(int) = delete; // but not with an integer
};
void f() {
Z z1 { 1 }; // error! can't use int
Z z2 { 1.0 }; // double is ok
}
=delete
的一些更高级的用法包括禁止堆栈或免费商店分配:class FS_Only {
~FS_Only() = delete; // disallow stack allocation
};
class Stack_Only {
void* operator new(size_t) = delete; // disallow heap allocation
};
...您明白了。希望这对某人有帮助!
=delete
可以帮助编写可读,无错误和优雅的代码。编辑:
正如注释中正确指出的那样,现在无法删除
FS_Only
对象,因此毕竟这不是对=delete
的很好使用。