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?
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)
beexplicit
, while the constructor ofpair
,(T first, U second)
be set non-explicit).