C++核心準(zhǔn)則C.44:默認(rèn)構(gòu)造函數(shù)最好簡單而且不會(huì)拋出異常
C.44: Prefer default constructors to be simple and non-throwing
C.44:默認(rèn)構(gòu)造函數(shù)最好簡單而且不會(huì)拋出異常
Reason(原因)Being able to set a value to "the default" without operations that might fail simplifies error handling and reasoning about move operations.
默認(rèn)構(gòu)造函數(shù)可以將內(nèi)容設(shè)置到默認(rèn)狀態(tài)而不需要可能引起失敗的操作,簡化了錯(cuò)誤處理和針對移動(dòng)操作的推測。
Example, problematic(問題示例)template
// 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:
? ?own elem;
? ?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
這段代碼整潔且普通,但是如果過在涉及到內(nèi)存分配的錯(cuò)誤之后生成一個(gè)空的Vector0對象時(shí),可能會(huì)失敗。同時(shí),讓默認(rèn)的Vector表現(xiàn)為{new T[0], 0, 0}有些浪費(fèi)。例如Vector0

100次內(nèi)存分配似乎有些問題。譯者的理解是只要一次分配100個(gè)整數(shù)的空間就好。
另外new T[0]有點(diǎn)奇怪。
Example(示例)template
// 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:
? ?own elem = nullptr;
? ?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{}的代價(jià)更小,但是特殊的情況,(由于產(chǎn)生了沒有數(shù)據(jù)的情況,譯者注)需要運(yùn)行時(shí)檢查。在檢測到錯(cuò)誤之后將Vector1設(shè)為空的處理是小事情。
Enforcement(實(shí)施建議)
Flag throwing default constructors.
提示拋出異常的構(gòu)造函數(shù)。
原文鏈接https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c44-prefer-default-constructors-to-be-simple-and-non-throwing
覺得本文有幫助?請分享給更多人。
關(guān)注【面向?qū)ο笏伎肌枯p松學(xué)習(xí)每一天!
面向?qū)ο箝_發(fā),面向?qū)ο笏伎迹?/span>

