c++中delete对象后 调用成员函数_C++核心准则C.81:如果不需要默认行为,使用=delete禁止它们

28e9b232430138344cbc6c8b452ef28a.png

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 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 make();   // make "something" and return it by movingvoid f(){    unique_ptr 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.

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

bb8786c1461c22a62aebf622c6cf8ba7.png

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

----Effective Modern C++

bb8786c1461c22a62aebf622c6cf8ba7.png

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


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

更多精彩文章请关注微信公众号【面向对象思考】!

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值