C.46: By default, declare single-argument constructors explicit
C.46: By default clearly defined single-argument constructor
Reason (reason)
To avoid unintended conversions.
Avoid unexpected conversion.
Example, bad (negative sample)
class String {
public:
String(int); // BAD
// ...
};
String s = 10; // surprise: string of size 10
Exception (exception)
If you really want an implicit conversion from the constructor argument type to the class type, don't use explicit:
If you do need to convert from a class constructor parameters like type of implicit type, without the use of explicit keywords.
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
See also: discussion of implicit type conversion.
Implicit type conversion of the discussion:
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Ro-conversion
Exception (exception)
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.
And moving the copy constructors should not be defined as explicit, it shall not be performed for that type conversion. Explicitly copy / move constructor argument passed by value, and that the return result difficult.
Enforcement (Suggestions)
(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".
Constructor (simple) unique parameters should be defined as explicit. Well-defined non-explicit single argument constructor is rare in most of the code. A warning to all not "positive list" in the case.
Description link
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c46-by-default-declare-single-argument-constructors-explicit
I think this article helpful? Welcome thumbs up and share it with more people.
Read more updated articles, please pay attention to micro-channel public number of object-oriented thinking []