C++核心准则:C.164:避免隐式转换运算符
共 1725字,需浏览 4分钟
·
2020-03-01 23:24
C.164: Avoid implicit conversion operators
C.164:避免隐式转换运算符
Reason(原因)
Implicit conversions can be essential (e.g., double to int) but often cause surprises (e.g., String to C-style string).
隐式转换可以很重要(例如,double转换为int),但经常会带来意外的结果(例如,String转换为C风格字符串)。
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.
优先采用显式命名转换,直到发现必须重视的需求。我们通过“必须重视的需求”来表达在应用领域中非常本质(例如整数到复数的转换)且经常遇到的原因。不要因为很小的便利而(通过转换运算符或者非显式构造函数)引入隐式转换。
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.,
意外的、具有潜在破坏的隐式转换可能在任何时候发生,而且难于发现。
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.
提示所有的转换运算符。
原文链接:
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c164-avoid-implicit-conversion-operators
觉得本文有帮助?请分享给更多人。
关注【面向对象思考】轻松学习每一天!
面向对象开发,面向对象思考!