When is reinterpret_cast used?

Asked 2 years ago, Updated 2 years ago, 61 views

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?

c++ casting

2022-09-22 10:51

1 Answers

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.


2022-09-22 10:51

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.