B
bjarne
James said:[...]
The problem with the C-style cast is that it converts
almost anything to almost anything else, which is seldom
what you want to do. Usually you only want to cast between
compatible types.
And sadly, C++-style functional casts have this same danger.
Except that the danger is only really present if the target
type is a pointer or a reference, and functional casts can't
be used in such cases.I consider this
enum colors { red, green, blue };
colors c = colors(10);
dangerous.
In the same sense that
int i = int( 3.14159 ) ;
is dangerous, yes. In the case of user defined types, you could
do some runtime checking, but only if you overloaded enough to
avoid the implicit conversions. Because in the end, if you have
MyClass, with a constructor which takes an int, what is the
different between:
int i = int( 3.14159 ) ;
and
MyClass c( 3.14159 ) ;
There is, IMHO, a real problem in that many such dangerous
conversions are not only allowed, but happen implicitly. IIRC,Stroustrup wanted to change this at one point, but the committee
wouldn't follow him. So we're more or less stuck with them.
More or less, but only more or less. In C++0x we'll get the uniform
initialization syntax and semantics based on { }, and that doesn't
allow narrowing, so
int i1 = int( 3.14159 ) ; // ok (unfortunately)
int i2 = 3.14; // ok (unfortunately)
int i3 = int{3.14}; // error: narrowing
int i3{3.14}; // error: narrowing
colors c1 = colors(10); // ok (unfortunately)
colors c2 = colors{10}; // error: narrowing
Bjarne Stroustrup; http://www.research.att.com/~bs