mercredi 1 février 2017

When to use explicit constructors (C++11)

I have read about the usage of explicit in constructors and some of its possible outcomes. There are many posts available at stack overflow but my primary problem is that I need some concrete points to bear in mind when designing a constructor and deciding about its convertibility. From my current research:

  1. I consider that explicit constructors are more verbose. This has both pros (no implicit conversions, more readable code) and cons (no converting constructors as return values, more to write).
  2. Additionally, with explicit constructors there cannot be copy initializations. In this case, I cannot grasp all the outcomes of such a behavior considering I am relatively new to C++. Copy constructors could be an exception.
  3. The context of the constructed class' usage also affects the decision of explicit.

So, I have two questions:

  • Are there any other points (at least for a beginner) to bear in mind?
  • Although the general rule to make single argument constructors explicit is not that suitable (implicit conversion to a multiple-argument constructor with C++11's list initializers) should it be followed?

I do not want to spur a debate so please guide me to edit the question if it needs rectification. Thank you for your time.

Aucun commentaire:

Enregistrer un commentaire