Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 458
Dave Mateer Avatar asked Apr 18 '11 13:04

Dave Mateer


2 Answers

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

like image 168
Johannes Schaub - litb Avatar answered Sep 23 '22 11:09

Johannes Schaub - litb


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.

like image 24
James Kanze Avatar answered Sep 22 '22 11:09

James Kanze