Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reinterpret_cast - bizarre behaviour

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!

like image 509
user2032932 Avatar asked Dec 21 '22 10:12

user2032932


1 Answers

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.

like image 57
Vaughn Cato Avatar answered Dec 24 '22 01:12

Vaughn Cato