문제

I've come across bizarre error related to reinterpret_cast. Just look at below code:

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

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

error in gcc 4.1.2: reinterpret_cast from type ‘int** ’ to type ‘const void** ’ casts away constness

error in gcc 4.6.2: reinterpret_cast from type ‘int** ’ to type ‘const void** ’ casts away qualifiers

Does anyone have a clue why compilers say that I'm casting const away. Me, and few of my work colleagues have no idea what's wrong with it.

Thanks for help!

도움이 되었습니까?

해결책

Section 5.2.10 of the C++03 standard talks about what a reinterpret_cast can do. It explicitly states "The reinterpret_cast operator shall not cast away constness".

Casting away constness is defined in section 5.2.11 of the C++03 standard. The notation used there is a little confusing, but it basically states that casting between two types "casts away constness" if there is no implicit conversion for the given qualification.

In your case, you are trying to convert an int ** to a void const**. The compiler asks "Can I implicitly convert between T ** and T const**?", and the answer is no, so it says that you are casting away constness.

The logic here is that reinterpret_cast is made to handle changing types, not changing qualifiers (that's what const_cast is for). So if you are asking it to do something you would need const_cast for, it refuses.

다른 팁

To add/remove const, use const_cast.

To deal with confusing casting errors, do things one step 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 an int** bob. You then pass it to a function that takes a int const** alice through a const_cast.

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

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top