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

共 1257字,需浏览 3分钟

 ·

2020-01-14 23:24

655a4b0ec672aeead9856d075c13a9b6.webp

斜方砷铁矿与方解石

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


template
class 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(反面示例)


template
class 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.

(简单)移动操作应该被声明为noexcept。




原文链接


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




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

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

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



浏览 14
点赞
评论
收藏
分享

手机扫一扫分享

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

手机扫一扫分享

分享
举报