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

面向对象思考

共 1508字,需浏览 4分钟

 · 2020-01-01

86edbb99b3b2e73fc556b27a60bd02f4.webp

28a441f3a12fb290ad49b1d2de943b74.webpC.46: By default, declare single-argument constructors explicitC.46:默认状态下明确定义单参数构造函数28a441f3a12fb290ad49b1d2de943b74.webp

73ae6ca43e3401ba4f6230525ab62f8e.webpReason(原因)73ae6ca43e3401ba4f6230525ab62f8e.webp

To avoid unintended conversions.

避免意外的转换。


73ae6ca43e3401ba4f6230525ab62f8e.webpExample, bad(反面示例)73ae6ca43e3401ba4f6230525ab62f8e.webp
class String {
public:
   String(int);   // BAD
   // ...
};

String s = 10;   // surprise: string of size 10

73ae6ca43e3401ba4f6230525ab62f8e.webpException(例外)73ae6ca43e3401ba4f6230525ab62f8e.webp

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


73ae6ca43e3401ba4f6230525ab62f8e.webpException(例外)73ae6ca43e3401ba4f6230525ab62f8e.webp

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.

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


73ae6ca43e3401ba4f6230525ab62f8e.webpEnforcement(实施建议)73ae6ca43e3401ba4f6230525ab62f8e.webp

(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单参数构造函数在大多数代码中很少见。对于所有不在“正面清单”中的情况进行警告。

73ae6ca43e3401ba4f6230525ab62f8e.webp原文链接73ae6ca43e3401ba4f6230525ab62f8e.webp

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



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

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

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

浏览 6
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报