I'm confused when to write reinterpret_cast
and static_cast
.
As far as I know, if you decide on type
when compile
, you use static cast
reinterpret_cast
is
in the case of I know it's a feature that you shouldn't use normally
I don't know which one to use in my code.
My code first points to C++ object
using void *
Convert this to Class type*
later.
In my case, which one should I use?
Is it better to cast when compiling with static
?
Since pointer type
is changed from void
to Class
, should we use reinterpret_cast
?
The C++ standard for the question is as follows:
In static_casting
, whether the pointer becomes void*
or the returned value is still preserved.(Address values are preserved even in the middle course)
That is, in the following example, a, b, and c store the same address value.
int* a = new int();
void* b = static_cast<void*>(a);
int* c = static_cast<int*>(b);
reinterpret_cast
is a different type of pointer
In addition, if cast
is returned to original type
, original value
is guaranteed. (I don't know what the address value will be during the intermediate process.)
That is, in the following example, a and c store the same address value, but b is unknown.
int* a = new int();
void* b = reinterpret_cast<void*>(a);
int* c = reinterpret_cast<int*>(b);
When casting void*
, static_cast
is preferred.
© 2024 OneMinuteCode. All rights reserved.