Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
800 views
in Technique[技术] by (71.8m points)

c++ - static_cast VS reinterpret_cast when casting pointers to pointers

Given the following conditions:

struct A
{
    int a;
};

struct B
{
    int b;
};

int main()
{
    A  a {1};
    A* p = &a;

Does casting with static_cast and with reinterpret_cast via void* give the same result? I.e is there any difference between the following expressions?

    static_cast      <A*> ( static_cast      <void*> (p) );
    reinterpret_cast <A*> ( reinterpret_cast <void*> (p) );

What if we cast pointer to one class to pointer to another class with static_cast and with reinterpret_cast? Is there any difference between these two operators? Are the following expressions the same?

    static_cast      <B*> ( static_cast      <void*> (p) );
    reinterpret_cast <B*> ( reinterpret_cast <void*> (p) );
    reinterpret_cast <B*> (                           p  );

Can I use B* pointer after this to access b member?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

is there any difference between the following expressions?

static_cast      <A*> ( static_cast      <void*> (p) );
reinterpret_cast <A*> ( reinterpret_cast <void*> (p) );

No.

Are the following expressions the same?

static_cast      <B*> ( static_cast      <void*> (p) );
reinterpret_cast <B*> ( reinterpret_cast <void*> (p) );
reinterpret_cast <B*> (                           p  );

Yes.

Easy way to understand this is to think about how reinterpret_cast from pointer to pointer is specified. reinterpret_cast<T*>(ptr) is specified to behave exactly the same as static_cast<T*>(static_cast<void*>(ptr)) (I've left out cv qualifiers for simplicity).

And of course, static_cast<T>(static_cast<T>(anything)) is equivalent to static_cast<T>(anything) because the outer cast is always an identity conversion.


Can I use B* pointer after this to access b member?

No. If you did that, then the behaviour of the program would be undefined.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...