Is there any downside to marking all C++ constructors explicit?

1.2k Views Asked by At

A few times, when refactoring code, I have forgotten to add the explicit keyword when adding a parameter to a previously-parameterless constructor, or removing parameters from a previously multi-parameter constructor. To prevent this, I have gotten in the habit of marking every constructor explicit, no matter no many arguments it has. (Except, of course, those constructors for which I actually want implicit conversion.)

Is there any downside to this? Performance? Compile time?

3

There are 3 best solutions below

0
On BEST ANSWER

It doesn't have any downsides. It will be future safe, because in C++0x multi-parameter constructors participate in initializations using multi-element initializer lists and can forbidden to be used in the cases where only implicit conversions apply using explicit.

So if you find out a give multi-parameter constructor does not logically represent the value of your class, I think it's good to make it explicit (example: I would set a container constructor (size_t size, T defaultValue) be explicit, while the constructor of pair, (T first, U second) be set non-explicit).

0
On

There will be no runtime performance difference. The compile time difference is likely to be undetectable.

I think there is no harm in declaring all constructors with arguments explicit, except that it might look redundant for those with more than one argument.

If you declare a type with an explicit default constructor, you may have trouble using it with collection types.

3
On

I'm not sure, but I think it does have some unexpected consequences for the copy constructor to be explicit. Other than that, I think yo're OK.