Reinterpret_cast - strange behavior

I came across a fancy error related to reinterpret_cast. See below code:

int* var; reinterpret_cast<void const **>(&var); 

error in VSC ++ 2010: error C2440: 'reinterpret_cast': cannot convert from 'int **' to 'const void **'

bug in gcc 4.1.2: reinterpret_cast of type 'int ** for input' const void ** discards a constant

bug in gcc 4.6.2: reinterpret_cast from type 'int ** for input' const void ** discards qualifiers

Does anyone know why compilers say that I am discarding const. I, and a few of my work colleagues, have no idea what is wrong with him.

Thanks for the help!

+4
source share
2 answers

Section 5.2.10 of the C ++ 03 standard talks about what reinterpret_cast can do. It explicitly states: "The reinterpret_cast statement shall not discard a constant."

The drop console is defined in section 5.2.11 of the C ++ 03 standard. The notation used here is a little confusing, but it basically says that casting between the two types "drops the constable" if there is no implicit conversion for this qualification.

In your case, you are trying to convert int ** to void const** . The compiler asks: β€œCan I implicitly convert between T ** and T const** ?”, But the answer is no, so it says that you drop the constant.

The logic here is that reinterpret_cast is designed to handle changing types, and not to change qualifiers (what const_cast is for). Therefore, if you ask him to do something for which you need const_cast, he will refuse.

+8
source

To add / remove const , use const_cast .

To deal with confusing casting errors, do something one at a time:

 int* var; int** v2 = &var; int const** v3 = const_cast<int const**>(v2); void const** v4 = reinterpret_cast<void const**>(v3); 

Note that a int const** and a int** are very different types, and converting between them is dangerous - more dangerous than a void* ↔ int* .

Suppose you have int** bob . Then you pass it to a function that takes int const** alice through const_cast .

In this function, they assign a pointer to an int stored in read-only memory, to *alice - completely legal.

Outside of the function, you check that bob and *bob valid, then assign **bob , and you just tried writing to read-only memory.

+2
source

All Articles