C++核心准则C.81:如果不需要默认(同时不需要其他选项)行为,使用=delete禁止它们

C.81: Use =delete when you want to disable default behavior (without wanting an alternative)

C.81:如果不需要默认(同时不需要其他选项)行为,使用=delete禁止它们

Reason(原因)

In a few cases, a default operation is not desirable.

某些情况下·,也有可能·不希望存在默认行为。

Example(示例)

class Immortal {
public:
    ~Immortal() = delete;   // do not allow destruction
    // ...
};

void use()
{
    Immortal ugh;   // error: ugh cannot be destroyed
    Immortal* p = new Immortal{};
    delete p;       // error: cannot destroy *p
}

Example(示例)

A unique_ptr can be moved, but not copied. To achieve that its copy operations are deleted. To avoid copying it is necessary to =delete its copy operations from lvalues:

独占指针可以被移动,但是不能被拷贝。为了实现这一点,代码禁止了拷贝操作。禁止拷贝的方法是将源自左值的拷贝操作声明为=delete。

template <class T, class D = default_delete<T>> class unique_ptr {
public:
    // ...
    constexpr unique_ptr() noexcept;
    explicit unique_ptr(pointer p) noexcept;
    // ...
    unique_ptr(unique_ptr&& u) noexcept;   // move constructor
    // ...
    unique_ptr(const unique_ptr&) = delete; // disable copy from lvalue
    // ...
};

unique_ptr<int> make();   // make "something" and return it by moving

void f()
{
    unique_ptr<int> pi {};
    auto pi2 {pi};      // error: no move constructor from lvalue
    auto pi3 {make()};  // OK, move: the result of make() is an rvalue
}

Note that deleted functions should be public.

注意:禁止的函数应该是公有的。

按照惯例,被删除函数(deleted functions)声明为public,而不是private。当用户代码尝试调用一个成员函数时,C++会在检查它的删除状态位之前检查它的可获取性(accessibility,即是否为public?)。当用户尝试调用一个声明为private的删除函数时,一些编译器会抱怨这些删除的函数被声明为private

----Effective Modern C++

Enforcement(实施建议)

The elimination of a default operation is (should be) based on the desired semantics of the class. Consider such classes suspect, but maintain a "positive list" of classes where a human has asserted that the semantics is correct.

消除默认操作(应该)应该基于类的期待语义。怀疑这些类,但同时维护类的“正面清单”,其内容是由人断定是正确的东西。

原文链接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c81-use-delete-when-you-want-to-disable-default-behavior-without-wanting-an-alternative


觉得本文有帮助?欢迎点赞并分享给更多的人。

阅读更多更新文章,请关注微信公众号【面向对象思考】

发布了408 篇原创文章 · 获赞 653 · 访问量 29万+

猜你喜欢

转载自blog.csdn.net/craftsman1970/article/details/104824952
今日推荐