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

共 2022字,需浏览 5分钟

 ·

2020-01-17 23:22

60915057ec0ed6ace72a51ee02ca85ba.webp


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

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



6bec2755796d05172bd213fd3922554c.webpReason(原因)

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

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


6bec2755796d05172bd213fd3922554c.webpExample(示例)
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
}
6bec2755796d05172bd213fd3922554c.webpExample(示例)
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 moving

void 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.

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


6ee205af2c86f45f6712b93d18dded30.webp

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

----Effective Modern C++

6ee205af2c86f45f6712b93d18dded30.webp16c6c30e97c2762522b045267690fc3d.webp6bec2755796d05172bd213fd3922554c.webpEnforcement(实施建议)

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.

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


6bec2755796d05172bd213fd3922554c.webp原文链接

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




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

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

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

浏览 41
点赞
评论
收藏
分享

手机扫一扫分享

分享
举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

分享
举报