构造函数= default;_C++核心准则C.46:默认状态下明确定义单参数构造函数

2c086bb0bbcea1337e36c419784fe72d.png

C.46: By default, declare single-argument constructors explicit

C.46:默认状态下明确定义单参数构造函数

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:

如果你确实需要一个从构造函数参数象类类型的隐式类型转换,不用适应explicit关键字。

class Complex {public:    Complex(double d);   // OK: we want a conversion from d to {d, 0}    // ...};Complex z = 10.7;   // unsurprising conversion

See also: Discussion of implicit conversions

参见:关于隐式类型转换的讨论。
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Ro-conversion

Note(注意)

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.

拷贝和移动构造函数不应该定义为explict,应为那样就不会执行类型转换了。显示拷贝/移动构造函数使通过值传递参数和返回结果变得困难。

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".

(简单)唯一参数的构造函数应该被定义为explicit。定义良好的非explicit单参数构造函数在大多数代码中很少见。对于所有不在“正面清单”中的情况进行警告。

原文链接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c46-by-default-declare-single-argument-constructors-explicit


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

更多精彩文章请关注微信公众号【面向对象思考】

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值