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(示例)
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
觉得本文有帮助?请分享给更多人。
更多精彩文章请关注微信公众号【面向对象思考】!
面向对象开发,面向对象思考!
,免责声明:本文仅代表文章作者的个人观点,与本站无关。其原创性、真实性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容文字的真实性、完整性和原创性本站不作任何保证或承诺,请读者仅作参考,并自行核实相关内容。文章投诉邮箱:anhduc.ph@yahoo.com