19

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?

Dave Mateer
  • 17,608
  • 15
  • 96
  • 149
  • similar: http://stackoverflow.com/questions/4607047/why-constructors-arent-explicit-by-default –  Apr 18 '11 at 13:21

3 Answers3

15

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

Johannes Schaub - litb
  • 496,577
  • 130
  • 894
  • 1,212
9

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.

James Kanze
  • 150,581
  • 18
  • 184
  • 329
  • good point with the copy constructor, I wonder the effect on pass/return by value. – Matthieu M. Apr 18 '11 at 14:23
  • It was explained to me once; my conclusion was just to not make copy constructors explicit, and not worry about the details. IIRC, yes, it meant that objects of that type could not be passed to functions by value. But I'm no longer sure. – James Kanze Apr 18 '11 at 15:56
  • This sounded familiar, and indeed: http://bytes.com/topic/c/answers/131511-explicit-copy-constructor. CWG 152, fixed in C++03. – MSalters Apr 19 '11 at 08:30
4

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.

Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285