C++ explicit constructor instance resolution

  • 2020-04-02 02:26:48
  • OfStack

According to the default of C language, the constructor with only one parameter also defines an implicit conversion to convert the data of the corresponding data type of the constructor into this kind of object, as shown below:


class String {
String ( const char* p ); //Initialize the value with the c-style string p
// ... 
}
String s1 = "hello"; //OK implicit conversion is equivalent to String s1 = String ("hello");

But sometimes this implicit conversion may not be necessary, as follows:


class String {
    String ( int n ); //The intent is to pre-assign n bytes to the string
String ( const char* p ); //Initialize the value with the c-style string p
// ... 
}

The following two ways are more normal:


String s2 ( 10 );  //OK allocates an empty string of 10 bytes
String s3 = String ( 10 ); //OK allocates an empty string of 10 bytes

Here are two more confusing ways to write it:


String s4 = 10; //Compile passed, also allocated 10 bytes of empty string
String s5 = 'a'; //Compile pass, allocate an empty string of int ('a') bytes

S4 and s5 implicitly convert an int and a char, respectively, into an empty string that allocates several bytes, which is misleading.
To avoid this error, we can declare the shown transformation, using the explicit keyword:


class String {
    explicit String ( int n ); //The intent is to pre-assign n bytes to the string
String ( const char* p ); //Initialize the value with the c-style string p
// ... 
}

When you add explicit, you suppress the implicit conversion of String (int n),
 
The following two ways are still correct:


String s2 ( 10 );  //OK allocates an empty string of 10 bytes
String s3 = String ( 10 ); //OK allocates an empty string of 10 bytes

The following two ways are not allowed:


String s4 = 10; //Compilation does not pass. Implicit conversions are not allowed
String s5 = 'a'; //Compilation does not pass. Implicit conversions are not allowed

As a result, explicit can sometimes be effective in preventing errors or misunderstandings caused by implicit conversions to constructors

Explicit only works with constructors to suppress implicit conversions. Such as:      


class  A{  
  A(int a);  
};  
int Function(A a);  

When calling     Function (2)     At 2     It will implicitly convert to     a.     Type. This situation is often not what the programmer wants, so to avoid it, write:      


class  A  {  
 explicit  A(int  a);  
};  
int  Function(A  a);  

This way, when Function(2) is called, the compiler gives an error message (unless the Function has an overloaded form with an int), which prevents errors from occurring without the programmer's knowledge.

Summary: explicit only works with constructors to suppress implicit conversions.


Related articles: