前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则C.66:保证移动操作不会抛出异常

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

作者头像
面向对象思考
发布2020-03-25 16:17:04
5410
发布2020-03-25 16:17:04
举报

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<typename T>
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<typename T>
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


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

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

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

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2020-01-14,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 面向对象思考 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档