Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can reinterpret_cast not convert an int to int?

My compiler is the latest VC++ 2013 RC.

void f() {     int n1 = 0;     int n2 = reinterpret_cast<int>(n1); // error C2440 } 

error C2440: 'reinterpret_cast' : cannot convert from 'int' to 'int'

Why can reinterpret_cast not be used in such an obvious case?

like image 409
xmllmx Avatar asked Sep 18 '13 08:09

xmllmx


People also ask

What is the purpose of Reinterpret_cast and how does it differ from a regular cast?

reinterpret_cast is a type of casting operator used in C++. It is used to convert a pointer of some data type into a pointer of another data type, even if the data types before and after conversion are different. It does not check if the pointer type and data pointed by the pointer is same or not.

What does Reinterpret_cast mean in C++?

The reinterpret_cast allows the pointer to be treated as an integral type. The result is then bit-shifted and XORed with itself to produce a unique index (unique to a high degree of probability). The index is then truncated by a standard C-style cast to the return type of the function.

What is the difference between static_cast and Reinterpret_cast?

static_cast only allows conversions like int to float or base class pointer to derived class pointer. reinterpret_cast allows anything, that's usually a dangerous thing and normally reinterpret_cast is rarely used, tipically to convert pointers to/from integers or to allow some kind of low level memory manipulation.

Can Reinterpret_cast throw?

No. It is a purely compile-time construct. It is very dangerous, because it lets you get away with very wrong conversions.


1 Answers

According to cppreference.com the following conversion is available only since C++11:

An expression of integral, enumeration, pointer, or pointer-to-member type can be converted to its own type. The resulting value is the same as the value of expression.

which may not be implemented in Visual Studio 2013 RC yet.

like image 145
Shoe Avatar answered Sep 28 '22 02:09

Shoe