C++核心准则C.66:保证移动操作不会抛出异常

网友投稿 488 2022-10-12

C++核心准则C.66:保证移动操作不会抛出异常

C++核心准则C.66:保证移动操作不会抛出异常

C.66: Make move operations noexcept

C.66:保证移动操作不会抛出异常

Reason(原因)

A throwing move violates most people's reasonably assumptions. A non-throwing move will be used more efficiently by standard-library and language facilities.

抛出异常的移动操作会破坏大多数人的符合逻辑的推测。不会抛出异常的移动可以被标准库和C++语言更加高效地使用。

Example(示例

templateclass Vector {public: Vector(Vector&& a) noexcept :elem{a.elem}, sz{a.sz} { a.sz = 0; a.elem = nullptr; } Vector& operator=(Vector&& a) noexcept { elem = a.elem; sz = a.sz; a.sz = 0; a.elem = nullptr; } // ...private: T* elem; int sz;};

These operations do not throw.

这些操作都不会抛出异常。

Example, bad(反面示例)

templateclass Vector2 {public: Vector2(Vector2&& a) { *this = a; } // just use the copy Vector2& operator=(Vector2&& a) { *this = a; } // just use the copy // ...private: T* elem; int sz;};

This Vector2 is not just inefficient, but since a vector copy requires allocation, it can throw.

Vector2的问题不止是效率低,由于拷贝时需要分配内存,它可能还会抛出异常。

Enforcement(实施建议)

(Simple) A move operation should be marked noexcept.

原文链接

​​https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c66-make-move-operations-noexcept​​

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

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

上一篇:基于电影知识图谱和微信小程序的智能问答系统
下一篇:C++核心准则C102-109:容器的基本要求
相关文章

 发表评论

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