C++核心準(zhǔn)則C.66:保證移動(dòng)操作不會(huì)拋出異常
斜方砷鐵礦與方解石
C.66: Make move operations noexceptC.66:保證移動(dòng)操作不會(huì)拋出異常
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.
拋出異常的移動(dòng)操作會(huì)破壞大多數(shù)人的符合邏輯的推測。不會(huì)拋出異常的移動(dòng)可以被標(biāo)準(zhǔn)庫和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.
這些操作都不會(huì)拋出異常。
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的問題不止是效率低,由于拷貝時(shí)需要分配內(nèi)存,它可能還會(huì)拋出異常。
Enforcement(實(shí)施建議)
(Simple) A move operation should be marked noexcept.
(簡單)移動(dòng)操作應(yīng)該被聲明為noexcept。
原文鏈接
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c66-make-move-operations-noexcept
覺得本文有幫助?請(qǐng)分享給更多人。
關(guān)注【面向?qū)ο笏伎肌枯p松學(xué)習(xí)每一天!
面向?qū)ο箝_發(fā),面向?qū)ο笏伎迹?/span>

