c哥教你實盤操作(核心準證C.66:保證移動操作不會拋出異常)
2023-09-16 16:20:43
斜方砷鐵礦與方解石
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.
(簡單)移動操作應該被聲明為noexcept。
原文連結
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c66-make-move-operations-noexcept
覺得本文有幫助?請分享給更多人。
更多精彩文章請關注微信公眾號【面向對象思考】!
面向對象開發,面向對象思考!
,