Need help understanding. The syntax {} -initializer minimizes the chances of unsuccessful conversions "

In "C ++ Programming Language" 4th edition p. 164:

When we explicitly specify the type of object that we initialize, we must consider two types: the type of the object and the type of initializer. For instance:

char v1 = 12345; // 12345 is an int
int v2 = 'c'; // 'c' is a char
T v3 = f();

Using the {} -initializer syntax for such definitions, we minimize the chances of bad conversions:

char v1 {12345}; // error : narrowing
int v2 {'c'}; // fine: implicit char->int conversion
T v3 {f()}; // works if and only if the type of f() can be implicitly converted to a T

I do not quite understand the suggestion minimize the chances for unfortunate conversionsand comment for T v3 {f()};what it is works if and only if the type of f() can be implicitly converted to a T. Consider the following two cases:

  • a) If T has an explicit constructor that takes an argument of type f ().
  • b) If type f () has a transform operator of some type X, and T has a constructor that takes an argument of type X.

f() T, T v3 {f()} , , , only if ? ( , if).

T v3 = f();, , minimize the chances for unfortunate conversions? , {} - ( ). ( v1, . v3.)

+3
3

-, .

, char x = 12345; 8 , char. {} , .

(ab) , ++, .

0

:

char v1 = 12345;

, , :

  • , 12345,
  • ,

v3 , . . ; , , ​​ . , , .

, , . .

0

v3:

T v3 {f()}; // works if and only if the type of f() can be implicitly converted to a T

is not strictly correct. This initialization works if and only if the type f()can be explicitly converted to T. This syntax:

T v3 = {f()}; // truly does work if and only if the type of f()
              // can be implicitly converted to a T

(initializing a list of copies instead of initializing a direct list) really requires the conversion to be implicit. The difference is illustrated by this program:

struct T {
  explicit T(int) {}
};

int f() { return 0; }

int main() {
  T v3 = {f()};
}

in which initialization will be diagnosed as incorrect, as it selects an explicit constructor for T( Live demo in Coliru ).

0
source

All Articles