3

In general, I've heard it's good practice to use the explicit keyword on constructors with a single argument. However, as of C++11, constructors with more than one argument can be used for implicit conversions. As such, is it good practice to apply the explicit keyword to ALL constructors of > 0 arguments?

Josh
  • 700
  • 5
  • 14

1 Answers1

0

The general rule for explicit is, do you want this constructor to be called implicitly?

If yes, don't make it explicit.

If no, make it explicit.

For 1 argument ctors, if converting from that type is as lossless and innocuous as converting an int to a double when needed, make it implicit.

For >1 argument ctors, determine if you want {} based construction to work. Sometimes it is a good idea, sometimes a bad idea.

In C++11 and 14, {} construction is needed in order to return a value from a function when the type cannot be moved or copied. In some cases, you'll use a tag type to make {} more explicit than it otherwise would be if you want to avoid "implicit {} usage" for whatever reason.

In C++17, there are fewer reasons to really need {} because prvalues are no longer objects but rather construction instructions; that means return T(blah) doesn't move/copy the T in a function returning T, but rather direction constructs it from blah.

When exactly you want to block {} is a matter of opinion, and not suitable for a SO Q&A.

Yakk - Adam Nevraumont
  • 262,606
  • 27
  • 330
  • 524