C.44: Prefer default constructors to be simple and non-throwing
C.44:默認構造函數最好簡單而且不會拋出異常
Reason(原因)
Being able to set a value to "the default" without operations that might fail simplifies error handling and reasoning about move operations.
默認構造函數可以將內容設置到默認狀態而不需要可能引起失敗的操作,簡化了錯誤處理和針對移動操作的推測。
Example, problematic(問題示例)
<code>template<typename>
// elem points to space-elem element allocated using new
class Vector0 {
public:
Vector0() :Vector0{0} {}
Vector0(int n) :elem{new T[n]}, space{elem + n}, last{elem} {}
// ...
private:
ownelem; /<typename>/<code>
T* space;
T* last;
};
This is nice and general, but setting a Vector0 to empty after an error involves an allocation, which may fail. Also, having a default Vector represented as {new T[0], 0, 0} seems wasteful. For example, Vector0
這段代碼整潔且普通,但是如果過在涉及到內存分配的錯誤之後生成一個空的Vector0對象時,可能會失敗。同時,讓默認的Vector表現為{new T[0], 0, 0}有些浪費。例如Vector0
譯者注:100次內存分配似乎有些問題。譯者的理解是隻要一次分配100個整數的空間就好。另外new T[0]有點奇怪。
Example(示例)
<code>template<typename>
// elem is nullptr or elem points to space-elem element allocated using new
class Vector1 {
public:
// sets the representation to {nullptr, nullptr, nullptr}; doesn't throw
Vector1() noexcept {}
Vector1(int n) :elem{new T[n]}, space{elem + n}, last{elem} {}
// ...
private:
ownelem = nullptr; /<typename>/<code>
T* space = nullptr;
T* last = nullptr;
};
Using {nullptr, nullptr, nullptr} makes Vector1{} cheap, but a special case and implies run-time checks. Setting a Vector1 to empty after detecting an error is trivial.
使用{nullptr, nullptr, nullptr}讓Vector1{}的代價更小,但是特殊的情況,(由於產生了沒有數據的情況,譯者注)需要運行時檢查。在檢測到錯誤之後將Vector1設為空的處理是小事情。
Enforcement(實施建議)
- Flag throwing default constructors.
- 提示拋出異常的構造函數。
原文鏈接
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c44-prefer-default-constructors-to-be-simple-and-non-throwing
覺得本文有幫助?請分享給更多人。
關注【面向對象思考】輕鬆學習每一天!
面向對象開發,面向對象思考!
閱讀更多 面向對象思考 的文章