[webkit-dev] Should we recommend explicit constructors as part of WebKit style?

Darin Adler darin at apple.com
Tue Sep 28 16:41:43 PDT 2010

On Sep 28, 2010, at 4:31 PM, Maciej Stachowiak wrote:

> I think the rule should be something like:
>   3. Do not explicit when the single-argument constructor can be thought of as a type conversion - the class will be in some sense an alternate form of its sole parameter. Do use explicit when the single-argument constructor is *not* reasonably thought of as a type conversion - the single argument just happens to be the sole initialization parameter. Or to put it another way - can you imagine having a type conversion operator overload that does the same thing as this constroctor?
> Applying this rule to your two examples, Vector(int) should be explicit, because it doesn't convert the int to a vector, it uses the int as a size instead of the default one. But String(AtomicString) or AtomicString(String) need not be explicit, since they convert from one string type to another, carrying largely the same data.
> I realize this rule requires some judgment, so it's worse than a purely mechanical rule, but I think it accurately captures the proper use of explicit.

This seems like a good rule. I agree completely that it’s the right principle.

When the conversion between types is costly enough, there may be some cases where we don’t want to offer an implicit constructor. Specifically, the implicit conversion from String to AtomicString may be a mistake; we might be better off if we had to utter some explicit function name every time we wanted a string looked up in the atomic string table.

I don’t think of this, though, as a rule for when to use “explicit”. It’s a rule for when to use a constructor that can be used implicitly for type conversion. If a constructor can’t be used that way, an explicit constructor might be OK, or you might not want the other constructor to exist at all. For example, if we want to be more explicit about the cost of looking up an AtomicString, the syntax for making an AtomicString from a String should probably be a named function, not AtomicString(string).

    -- Darin

More information about the webkit-dev mailing list