W jaki sposób zdefiniowalibyście zasady dodawania explicit do konstruktora?
Dość jasne jest, że konstruktor posiadający jeden argument powinien być explicit z wyjątkiem sytuacji, gdzie chcemy mieć konwersję. Co w przypadku konstruktorów wieloargumentowych, czy dobrą praktyką jest zawsze oznaczanie konstruktora jako explicit?
Tak. Od C++11 i możliwości inicjalizacji z {}
też zachodzą przypadki, gdzie wieloargumentowy konstruktor będzie użyty w sposób niejawny.
Cepo napisał(a):
W jaki sposób zdefiniowalibyście zasady dodawania explicit do konstruktora?
Zawsze jeśli konwersja z konstruktora jest groźna, czyli np gdy konstruktor przyjmuje jeden argument.
CppCoreGuidelines/CppCoreGuidelines.md at master · isocpp/CppCoreGuidelines
C.46: By default, declare single-argument constructors explicit
Reason
To avoid unintended conversions.
Example, bad
class String { public: String(int); // BAD // ... }; String s = 10; // surprise: string of size 10
Exception
If you really want an implicit conversion from the constructor argument type to the class type, don't use
explicit
:class Complex { public: Complex(double d); // OK: we want a conversion from d to {d, 0} // ... }; Complex z = 10.7; // unsurprising conversion
See also: Discussion of implicit conversions
Note
Copy and move constructors should not be made
explicit
because they do not perform conversions. Explicit copy/move constructors make passing and returning by value difficult.Enforcement
(Simple) Single-argument constructors should be declared
explicit
. Good single argument non-explicit
constructors are rare in most code bases. Warn for all that are not on a "positive list".