C++核心準(zhǔn)則:C.164:避免隱式轉(zhuǎn)換運算符

C.164: Avoid implicit conversion operators
C.164:避免隱式轉(zhuǎn)換運算符
Reason(原因)
Implicit conversions can be essential (e.g.,?double?to?int) but often cause surprises (e.g.,?String?to C-style string).
隱式轉(zhuǎn)換可以很重要(例如,double轉(zhuǎn)換為int),但經(jīng)常會帶來意外的結(jié)果(例如,String轉(zhuǎn)換為C風(fēng)格字符串)。
Note(注意)
Prefer explicitly named conversions until a serious need is demonstrated. By "serious need" we mean a reason that is fundamental in the application domain (such as an integer to complex number conversion) and frequently needed. Do not introduce implicit conversions (through conversion operators or non-explicit constructors) just to gain a minor convenience.
優(yōu)先采用顯式命名轉(zhuǎn)換,直到發(fā)現(xiàn)必須重視的需求。我們通過“必須重視的需求”來表達(dá)在應(yīng)用領(lǐng)域中非常本質(zhì)(例如整數(shù)到復(fù)數(shù)的轉(zhuǎn)換)且經(jīng)常遇到的原因。不要因為很小的便利而(通過轉(zhuǎn)換運算符或者非顯式構(gòu)造函數(shù))引入隱式轉(zhuǎn)換。
Example(示例)
struct S1 {
string s;
// ...
operator char*() { return s.data(); } // BAD, likely to cause surprises
};
struct S2 {
string s;
// ...
explicit operator char*() { return s.data(); }
};
void f(S1 s1, S2 s2)
{
char* x1 = s1; // OK, but can cause surprises in many contexts
char* x2 = s2; // error (and that's usually a good thing)
char* x3 = static_cast(s2); // we can be explicit (on your head be it)
}
The surprising and potentially damaging implicit conversion can occur in arbitrarily hard-to spot contexts, e.g.,
意外的、具有潛在破壞的隱式轉(zhuǎn)換可能在任何時候發(fā)生,而且難于發(fā)現(xiàn)。
S1 ff();
char* g()
{
return ff();
}
The string returned by?ff()?is destroyed before the returned pointer into it can be used.
被ff()返回的string對象會在返回的指針被使用之前被銷毀。
Enforcement(實施建議)
Flag all conversion operators.
提示所有的轉(zhuǎn)換運算符。
原文鏈接:
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c164-avoid-implicit-conversion-operators
覺得本文有幫助?請分享給更多人。
關(guān)注【面向?qū)ο笏伎肌枯p松學(xué)習(xí)每一天!
面向?qū)ο箝_發(fā),面向?qū)ο笏伎迹?/span>
