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

网友投稿 196 2022-12-02

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:

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.

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

----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​​

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

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:springboot 如何解决cross跨域请求的问题
下一篇:C++核心准则C.89:保证哈希不会抛出异常
相关文章

 发表评论

暂时没有评论,来抢沙发吧~