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
覺得本文有幫助?歡迎點贊並分享給更多的人。
閱讀更多更新文章,請關注微信公衆號【面向對象思考】