C++核心準則C.46:默認狀態(tài)下明確定義單參數(shù)構造函數(shù)

C.46: By default, declare single-argument constructors explicitC.46:默認狀態(tài)下明確定義單參數(shù)構造函數(shù)
Reason(原因)
To avoid unintended conversions.
避免意外的轉換。
Example, bad(反面示例)
class String {
public:
? ?String(int); ? // BAD
? ?// ...
};
String s = 10; ? // surprise: string of size 10
Exception(例外)
If you really want an implicit conversion from the constructor argument type to the class type, don't use explicit:
如果你確實需要一個從構造函數(shù)參數(shù)象類類型的隱式類型轉換,不用使用explicit關鍵字。
class Complex {
public:
? ?Complex(double d); ? // OK: we want a conversion from d to {d, 0}
? ?// ...
};
Complex z = 10.7; ? // unsurprising conversionSee also: Discussion of implicit conversions
參見:關于隱式類型轉換的討論。
隱式類型轉換的討論:
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Ro-conversion
Exception(例外)
Copy and move constructors should not be made explicit because they do not perform conversions. Explicit copy/move constructors make passing and returning by value difficult.
拷貝和移動構造函數(shù)不應該定義為explicit,應為那樣就不會執(zhí)行類型轉換了。顯式拷貝/移動構造函數(shù)使通過值傳遞參數(shù)和返回結果變得困難。
Enforcement(實施建議)
(Simple) Single-argument constructors should be declared explicit. Good single argument non-explicit constructors are rare in most code bases. Warn for all that are not on a "positive list".
(簡單)唯一參數(shù)的構造函數(shù)應該被定義為explicit。定義良好的非explicit單參數(shù)構造函數(shù)在大多數(shù)代碼中很少見。對于所有不在“正面清單”中的情況進行警告。
原文鏈接
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c46-by-default-declare-single-argument-constructors-explicit
覺得本文有幫助?請分享給更多人。
關注【面向對象思考】輕松學習每一天!
面向對象開發(fā),面向對象思考!
