Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any real example of reinterpret_cast changing a pointer value?

According to C++ Standard, a reinterpret_cast of a pointer T* to some other type pointer Q* can change or not change the pointer value depending on implementation.

I'm very interested - it there any real example of a C++ implementation where casting a pointer to some other pointer type with reinterpret_cast changes the pointer? What and why is changed there?

like image 520
sharptooth Avatar asked Jul 21 '10 11:07

sharptooth


People also ask

Is it safe to use Reinterpret_cast?

The result of a reinterpret_cast cannot safely be used for anything other than being cast back to its original type. Other uses are, at best, nonportable. The reinterpret_cast operator cannot cast away the const , volatile , or __unaligned attributes.

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.

What is a static_cast in C++?

The static_cast operator converts variable j to type float . This allows the compiler to generate a division with an answer of type float . All static_cast operators resolve at compile time and do not remove any const or volatile modifiers.

Is reinterpret cast compile time?

None of the casts happen at compile time. You only have the data at runtime, in general.


1 Answers

Note that when the standard states that it can or cannot possibly do something, it does not mean that there is any current implementation that has that behavior, only that they could.

The closest that I can think of is an architecture where type alignment was required by the hardware, and an implementation that decided to correct alignment if needed. Something like:

aligned8 var;
aligned1 *p = reinterpret_cast<aligned1*>(&var);
aligned1 *q = p + 1; // assuming aligned 1 size is not multiple of 8
aligned8 *a = reinterpret_cast<aligned8*>(q); // [1]

There could be a requirement that for a to be a valid pointer it has to address a memory position multiple of 8, while the argument q with lesser alignment requirements could point to any memory address.

like image 96
David Rodríguez - dribeas Avatar answered Oct 17 '22 07:10

David Rodríguez - dribeas