reinterpret_cast
conversionGeneral topics | ||||||||||||||||
Flow control | ||||||||||||||||
Conditional execution statements | ||||||||||||||||
Iteration statements (loops) | ||||||||||||||||
Jump statements | ||||||||||||||||
Functions | ||||||||||||||||
Function declaration | ||||||||||||||||
Lambda function expression | ||||||||||||||||
inline specifier | ||||||||||||||||
Dynamic exception specifications(until C++17*) | ||||||||||||||||
noexcept specifier(C++11) | ||||||||||||||||
Exceptions | ||||||||||||||||
Namespaces | ||||||||||||||||
Types | ||||||||||||||||
Specifiers | ||||||||||||||||
| ||||||||||||||||
Storage duration specifiers | ||||||||||||||||
Initialization | ||||||||||||||||
Expressions | ||||||||||||||||
Alternative representations | ||||||||||||||||
Literals | ||||||||||||||||
Boolean -Integer -Floating-point | ||||||||||||||||
Character -String -nullptr(C++11) | ||||||||||||||||
User-defined(C++11) | ||||||||||||||||
Utilities | ||||||||||||||||
Attributes(C++11) | ||||||||||||||||
Types | ||||||||||||||||
typedef declaration | ||||||||||||||||
Type alias declaration(C++11) | ||||||||||||||||
Casts | ||||||||||||||||
| ||||||||||||||||
Memory allocation | ||||||||||||||||
Classes | ||||||||||||||||
Class-specific function properties | ||||||||||||||||
| ||||||||||||||||
Special member functions | ||||||||||||||||
Templates | ||||||||||||||||
Miscellaneous | ||||||||||||||||
General | |||||||||||||||||||||
Literals | |||||||||||||||||||||
Operators | |||||||||||||||||||||
Conversions | |||||||||||||||||||||
|
Converts between types by reinterpreting the underlying bit pattern.
Contents |
reinterpret_cast< target-type>( expression) | |||||||||
Returns a value of typetarget-type.
Unlikestatic_cast, but likeconst_cast, thereinterpret_cast expression does not compile to any CPU instructions (except when converting between integers and pointers, or between pointers on obscure architectures where pointer representation depends on its type). It is primarily a compile-time directive which instructs the compiler to treatexpression as if it had the typetarget-type.
Only the following conversions can be done withreinterpret_cast, except when such conversions wouldcast away constness (or volatility).
static_cast
orimplicit conversion should be used for this purpose.4) Any value of typestd::nullptr_t, includingnullptr can be converted to any integral type as if it were(void*)0, but no value, not evennullptr can be converted tostd::nullptr_t:static_cast should be used for that purpose. | (since C++11) |
T1*
can be converted to another object pointer typecv T2*
. This is exactly equivalent tostatic_cast<cv T2*>(static_cast<cv void*>(expression)) (which implies that ifT2
's alignment requirement is not stricter thanT1
's, the value of the pointer does not change and conversion of the resulting pointer back to its original type yields the original value). In any case, the resulting pointer may only be dereferenced safely if the dereferenced value istype-accessible.T1
can be converted to reference to another typeT2
. The result is that of*reinterpret_cast<T2*>(p), wherep is a pointer of type “pointer toT1
” to the object or function designated byexpression. No temporary ismaterialized or(since C++17) created, no copy is made, no constructors or conversion functions are called. The resulting reference can only be accessed safely if it istype-accessible.dlsym
), a function pointer can be converted tovoid* or any other object pointer, or vice versa. If the implementation supports conversion in both directions, conversion to the original type yields the original value, otherwise the resulting pointer cannot be dereferenced or called safely.T1
can be converted to a pointer to another member object of another classT2
. IfT2
's alignment is not stricter thanT1
's, conversion back to the original typeT1
yields the original value, otherwise the resulting pointer cannot be used safely.As with all cast expressions, the result is:
| (since C++11) |
If a typeT_ref
issimilar to any of the following types, an object ofdynamic typeT_obj
istype-accessible through alvalue(until C++11)glvalue(since C++11) of typeT_ref
:
T_obj
T_obj
If a program attempts to read or modify the stored value of an object through alvalue(until C++11)glvalue(since C++11) through which it is not type-accessible, the behavior is undefined.
This rule enables type-based alias analysis, in which a compiler assumes that the value read through a glvalue of one type is not modified by a write to a glvalue of a different type (subject to the exceptions noted above).
Note that many C++ compilers relax this rule, as a non-standard language extension, to allow wrong-type access through the inactive member of aunion (such access is not undefined in C).
If any of the following conditions is satisfied, a typeT_call
iscall-compatible with a function typeT_func
:
T_call
is the same type asT_func
.
| (since C++17) |
If a function is called through an expression whosefunction type is not call-compatible with the type of the called function’s definition, the behavior is undefined.
Assuming that alignment requirements are met, areinterpret_cast does not change thevalue of a pointer outside of a few limited cases dealing withpointer-interconvertible objects:
struct S1{int a;} s1;struct S2{int a;private:int b;} s2;// not standard-layoutunion U{int a;double b;} u={0};int arr[2]; int* p1=reinterpret_cast<int*>(&s1);// value of p1 is "pointer to s1.a" because// s1.a and s1 are pointer-interconvertible int* p2=reinterpret_cast<int*>(&s2);// value of p2 is unchanged by reinterpret_cast// and is "pointer to s2". int* p3=reinterpret_cast<int*>(&u);// value of p3 is "pointer to u.a":// u.a and u are pointer-interconvertible double* p4=reinterpret_cast<double*>(p3);// value of p4 is "pointer to u.b": u.a and// u.b are pointer-interconvertible because// both are pointer-interconvertible with u int* p5=reinterpret_cast<int*>(&arr);// value of p5 is unchanged by reinterpret_cast// and is "pointer to arr"
Performing a class member access that designates a non-static data member or a non-static member function on a glvalue that does not actually designate an object of the appropriate type - such as one obtained through areinterpret_cast - results in undefined behavior:
struct S{int x;};struct T{int x;int f();};struct S1: S{};// standard-layoutstruct ST: S, T{};// not standard-layout S s={};auto p=reinterpret_cast<T*>(&s);// value of p is "pointer to s"auto i= p->x;// class member access expression is undefined behavior;// s is not a T objectp->x=1;// undefined behaviorp->f();// undefined behavior S1 s1={};auto p1=reinterpret_cast<S*>(&s1);// value of p1 is "pointer to the S subobject of s1"auto i= p1->x;// OKp1->x=1;// OK ST st={};auto p2=reinterpret_cast<S*>(&st);// value of p2 is "pointer to st"auto i= p2->x;// undefined behaviorp2->x=1;// undefined behavior
Many compilers issue "strict aliasing" warnings in such cases, even though technically such constructs run afoul of something other than the paragraph commonly known as the "strict aliasing rule".
The purpose of strict aliasing and related rules is to enable type-based alias analysis, which would be decimated if a program can validly create a situation where two pointers to unrelated types (e.g., anint* and afloat*) could simultaneously exist and both can be used to load or store the same memory (seethis email on SG12 reflector). Thus, any technique that is seemingly capable of creating such a situation necessarily invokes undefined behavior.
When it is needed to interpret the bytes of an object as a value of a different type,std::memcpyorstd::bit_cast(since C++20) can be used:
double d=0.1;std::int64_t n;static_assert(sizeof n== sizeof d);// n = *reinterpret_cast<std::int64_t*>(&d); // Undefined behaviorstd::memcpy(&n,&d, sizeof d);// OKn=std::bit_cast<std::int64_t>(d);// also OK
If the implementation providesstd::intptr_t and/orstd::uintptr_t, then a cast from a pointer to an object type orcvvoid to these types is always well-defined. However, this is not guaranteed for a function pointer. | (since C++11) |
In C, aggregate copy and assignment access the aggregate object as a whole. But in C++ such actions are always performed through a member function call, which accesses the individual subobjects rather than the entire object (or, in the case of unions, copies the object representation, i.e., viaunsignedchar).
Demonstrates some uses ofreinterpret_cast:
#include <cassert>#include <cstdint>#include <iostream> int f(){return42;} int main(){int i=7; // pointer to integer and backstd::uintptr_t v1=reinterpret_cast<std::uintptr_t>(&i);// static_cast is an errorstd::cout<<"The value of &i is "<<std::showbase<<std::hex<< v1<<'\n';int* p1=reinterpret_cast<int*>(v1);assert(p1==&i); // pointer to function to another and backvoid(*fp1)()=reinterpret_cast<void(*)()>(f);// fp1(); undefined behaviorint(*fp2)()=reinterpret_cast<int(*)()>(fp1);std::cout<<std::dec<< fp2()<<'\n';// safe // type aliasing through pointerchar* p2=reinterpret_cast<char*>(&i);std::cout<<(p2[0]=='\x7'?"This system is little-endian\n":"This system is big-endian\n"); // type aliasing through referencereinterpret_cast<unsignedint&>(i)=42;std::cout<< i<<'\n'; [[maybe_unused]]constint&const_iref= i;// int &iref = reinterpret_cast<int&>(// const_iref); // compiler error - can't get rid of const// Must use const_cast instead: int &iref = const_cast<int&>(const_iref);}
Possible output:
The value of &i is 0x7fff352c358042This system is little-endian42
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
DR | Applied to | Behavior as published | Correct behavior |
---|---|---|---|
CWG 195 | C++98 | conversion between function pointers and object pointers not allowed | made conditionally-supported |
CWG 658 | C++98 | the result of pointer conversions was unspecified (except for conversions back to the original type) | specification provided for pointers whose pointed-to types satisfy the alignment requirements |
CWG 799 | C++98 | it was unclear which identity conversion can be done byreinterpret_cast | made clear |
CWG 1268 | C++11 | reinterpret_cast could only cast lvalues to reference types | xvalues also allowed |
CWG 2780 | C++98 | reinterpret_cast could not cast function lvalues to other reference types | allowed |
CWG 2939 | C++17 | reinterpret_cast could cast prvalues to rvalue reference types | not allowed |
const_cast conversion | adds or removes const[edit] |
static_cast conversion | performs basic conversions[edit] |
dynamic_cast conversion | performs checked polymorphic conversions[edit] |
explicit casts | permissive conversions between types[edit] |
standard conversions | implicit conversions from one type to another[edit] |
(C++20) | reinterpret the object representation of one type as that of another (function template)[edit] |