简体   繁体   English

我真的应该大量引入显式关键字吗?

[英]Should I really massively introduce the explicit keyword?

When I used the (recently released) Cppcheck 1.69 on my code 1 , it showed a whole lot of messages where I expected none.当我在我的代码1上使用(最近发布的)Cppcheck 1.69 时,它显示了很多我期望没有的消息。 Disabling noExplicitConstructor proved that all of them were of exactly this kind.禁用noExplicitConstructor证明它们都属于这种类型。

But I found that I'm not the only one with a lot of new Cppcheck messages, look at the results of the analysis of LibreOffice (which I'm allowed to show in public):但是我发现我不是唯一一个有很多新 Cppcheck 消息的人,看看 LibreOffice 的分析结果(我被允许公开展示):

LibreOffice 代码上的 Cppcheck 结果截图

What would an experienced programmer do:有经验的程序员会做什么:

  • Suppress the check?取消支票?
  • Massively introduce the explicit keyword?大量引入explicit关键字?

1 This is of course not my code but code I have to work at work, it's legacy code: a mix of C and C++ in several (pre-)standard flavors (let's say C++98), and it's a pretty large code base. 1这当然不是我的代码,而是我必须在工作中工作的代码,它是遗留代码:C 和 C++ 的几种(预)标准风格的混合(假设是 C++98),这是一个非常大的代码根据。

I've been bitten in the past by performance hits introduced by implicit conversions as well as outright bugs.过去,我一直被隐式转换带来的性能影响以及彻底的错误所困扰。 So I tend to always use explicit for all constructors that I do not want to participate in implicit conversions so that the compiler can help me catch my errors - and I then try to always also add a "// implicit intended" comment to the ctors where I explicitly intend for them to be used as converting ctors implicitly.所以我倾向于总是对我不想参与隐式转换的所有构造函数使用explicit ,以便编译器可以帮助我捕获我的错误 - 然后我总是尝试向构造函数添加“//隐式意图”注释我明确打算将它们用作隐式转换构造函数。 I find that this helps me write more correct code with fewer surprises.我发现这可以帮助我编写更正确的代码,而且意外更少。

… So I'd say "yes, go add explicit " - in the long run you'll be glad you did - that's what I did when I first learned about it, and I'm glad I did. ......所以我会说“是的,去添加explicit ” - 从长远来看,你会很高兴你做到了 - 这就是我第一次知道它时所做的,我很高兴我做到了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM