= delete有什么用途?

时间:2013-09-17 05:15:52

标签: c++ c++11 delete-operator

今天早些时候我问a question导致了另一个:我应该何时使用=delete?我认为在SO上只有一篇专门针对=delete的帖子,所以我在一本名为“The C ++ Programming Language”的书中查阅了它。我将在下面的答案中列出我的发现。

如果有更多话要说或者我错了,请发表评论或回答。

1 个答案:

答案 0 :(得分:29)

事实证明=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的好用。