One day, if you write a class that can be constructed only with a specific data type, you will habitually declare a default constructor and declare it as private. Do not call the default constructor to declare this class. However, I have received an email from the lead. It is recommended that you use the explicit statement. Private is not recommended.
In the Lazy habit, I returned an OK message. I accidentally saw the email today and found it wrong.
Let's talk with the code:
Class mystr {protected: char * STR _; public: mystr (void) // default constructor. Do nothing: Str _ (nullptr) {} mystr (int I) // a constructor with the int type and does nothing: Str _ (nullptr ){}}
No matter whether I call mystr S = 'a'; or call mystr S = 1; the constructor mystr (int I) will be called. The type conversion is implemented by default. in particular, this kind of seemingly reasonable conversion can still be compiled by changing the outrageous mystr S = "test", and only one warning is received at most: Multi-character constant, some compilation may not be allowed, or an error will be reported if the warning level is higher, but this is not the conversion I want. c ++ is such a language full of various pitfalls,
If explicit it is added, the compiler is not allowed to perform this conversion.
In summary, all single-parameter constructor should declare explicit to avoid the compiler from performing various explicit type conversions.
Referencing Objective C ++: constructor declared as explicit is generally more popular than its non-explicit brother. They prevent the compiler from executing unexpected (and often not expected) type conversions. Unless I have a good reason to allow the constructor to be used for implicit type conversion, I will declare it as explicit. I encourage you to follow the same policy.
Declare the default constructor as private. In my opinion, it is very simple. It is either a singleton or an object that only calls the constructor I provide.
Most of the time, I think the better way is to declare the copy constructor and operator = (Value assignment operator overload) to private.
External users of a class are prohibited from performing copy operations on the objects of this class. Open these operations when necessary.
Why can't the compiler provide a default secure closed class? When necessary, apply for various features. Do not give the class security to unreliable coders. Most of the time we write our own code, we do not know the danger of our code. C ++ is so confident in coders that Most coders are extremely unreliable.