前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则:C.164:避免隐式转换运算符

C++核心准则:C.164:避免隐式转换运算符

作者头像
面向对象思考
发布2020-03-25 16:58:44
4280
发布2020-03-25 16:58:44
举报

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(示例)

代码语言:javascript
复制
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<char*>(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.,

意外的、具有潜在破坏的隐式转换可能在任何时候发生,而且难于发现。

代码语言:javascript
复制
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


觉得本文有帮助?请分享给更多人。

关注【面向对象思考】轻松学习每一天!

面向对象开发,面向对象思考!

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2020-03-01,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 面向对象思考 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • C.164: Avoid implicit conversion operators
  • Reason(原因)
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档