What are the consequences of ignoring narrowing transforms in C ++ 0x

Starting with the inclusion of the C ++ 0x standard in g ++, I began to see “narrowing conversion” errors, especially when converting from "int" to "short", although I understand that the error covers a much wider range of conversions .

Can anyone shed light on the rational introduction of this extra layer of security? What are the possible consequences of disabling this error? (except for potential loss of accuracy).

Thanks.

+7
source share
1 answer

From Assignment and Compound Assignment Operators [expr.ass]

the value x = {v}, where T is the scalar type of the expression x, is the value x = T (v), except that no narrowing of the transformation (8.5.4) is allowed.

and List-initialization [dcl.ini.list]

If converting any of the arguments requires narrowing the transform (see below), the program is poorly formed.

Thus, you cannot ignore it; your program is poorly formed in the presence of narrowing conversions.

From Conformance to implementation :

Implementations are needed to diagnose programs that use extensions that are poorly formed in accordance with this International Standard. However, by doing this, they can compile and execute such programs.

Bjarne Stroustroup will say this :

Narrowing prevention

Problem: C and C ++ are implicitly truncated:

  int x = 7.3;  // Ouch!
     void f (int);
     f (7.3);  // Ouch! 

However, in C ++ 0x, the initialization of {} does not narrow down:

int x0 {7.3}; // error: narrowing int x1 = {7.3}; // error: narrowing double d = 7; int x2{d}; // error: narrowing (double to int) char x3{7}; // ok: even though 7 is an int, this is not narrowing vector<int> vi = { 1, 2.3, 4, 5.6 }; // error: double to int narrowing 

The C ++ 0x method avoids many incompatibilities by relying on the actual values ​​of the initializers (for example, 7 in the above example), when it can (and not just enter the type) when deciding to narrow the conversion. If the value can be represented exactly as the target type, the conversion is not narrowed.

 char c1{7}; // OK: 7 is an int, but it fits in a char char c2{77777}; // error: narrowing 

Please note that floating point and integer conversions are considered convergent - even from 7.0 to 7.

Thus, narrowing also increases type safety.

+11
source

All Articles