conversion syntax

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
 
H

Hendrik Schober

bjarne said:
[...]
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

Sounds good to me.

Schobi
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,169
Messages
2,570,919
Members
47,459
Latest member
Vida00R129

Latest Threads

Top