Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
423 views
in Technique[技术] by (71.8m points)

c++ - Why doesn't this reinterpret_cast compile?

I understand that reinterpret_cast is dangerous, I'm just doing this to test it. I have the following code:

int x = 0;
double y = reinterpret_cast<double>(x);

When I try to compile the program, it gives me an error saying

invalid cast from type 'float' to type 'double

What's going on? I thought reinterpret_cast was the rogue cast that you could use to convert apples to submarines, why won't this simple cast compile?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In C++ reinterpret_cast can only perform a specific set of conversions, explicitly listed in the language specification. In short, reinterpret_cast can only perform pointer-to-pointer conversions and reference-to-reference conversions (plus pointer-to-integer and integer-to-pointer conversions). This is consistent with the intent expressed in the very name of the cast: it is intended to be used for pointer/reference reinterpretation.

What you are trying to do is not reinterpretation. If you want to reinterpret an int as a double you'd have to convert it to a reference type

double y = reinterpret_cast<double&>(x); 

although the equivalent pointer-based reinterpretation is probably more explicit

double y = *reinterpret_cast<double*>(&x); // same as above

Note though, that while reinterpret_cast can convert the reference/pointer types, the actual attempt to read the data through the resultant reference/pointer produces undefined behavior.

And in any case this, of course, can't make much sense on a platform with int and double of different size (since in case of larger double you will read beyond the memory occupied by x).

So, in the end it all boils down to what you were trying to achieve. Memory reinterpretation? See above. Some kind of more meaningful int to double conversion? If so, reinterpret_cast won't help you here.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...