前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则C.81:如果不需要默认(同时不需要其他选项)行为,使用=delete禁止它们

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

作者头像
面向对象思考
发布2020-03-25 16:21:10
4650
发布2020-03-25 16:21:10
举报
文章被收录于专栏:C++核心准则原文翻译

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(示例)

代码语言:javascript
复制
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。

代码语言:javascript
复制
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


觉得本文有帮助?请分享给更多人。

关注【面向对象思考】轻松学习每一天!

面向对象开发,面向对象思考!

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2020-01-17,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 面向对象思考 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 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:
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档