Wolf
Wolf

Reputation: 10238

Should I really massively introduce the explicit keyword?

When I used the (recently released) Cppcheck 1.69 on my code1, it showed a whole lot of messages where I expected none. Disabling noExplicitConstructor proved that all of them were of exactly this kind.

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):

screenshot of Cppcheck results on LibreOffice code

What would an experienced programmer do:


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.

Upvotes: 10

Views: 3586

Answers (2)

usr1234567
usr1234567

Reputation: 23394

The C++ Core Guidelines state:

By default, declare single-argument constructors explicit to avoid unintended conversions.

Unless you want implicit conversion or for copy/move constructors.

Source: https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Rc-explicit

Upvotes: 0

Jesper Juhl
Jesper Juhl

Reputation: 31459

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

Upvotes: 13

Related Questions