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)
be explicit
, while the constructor of pair
, (T first, U second)
be set non-explicit).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With