Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

c++ - reinterpret_cast from object to first member

I was looking at this answer and I was wondering if casting an object to its first member with reinterpret_cast and using the result could be safe in C++.

Let's assume that we have a class A, a class B and an instance b of B:

class A{
public:
    int i;
    void foo(){}
};

class B{
public:
    A a;
};

B b;

Question 1: Is it safe to use b.a like this: reinterpret_cast<A*>(&b)->foo()?

Note: In the general case we suppose that the class and its member are both standard layout.

My lecture of the available references on reinterpret_cast tells me such usage should be authorized as there is no aliasing violation, however it conflicts with many answers like this one.

Question2: Is it safe to use b.a like this: static_cast<A*>(static_cast<void*>(&b))->foo()?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Yes, because both classes here are standard-layout types, you can convert between &b and &b.a.

reinterpret_cast<A*>(p) is defined to be the same as static_cast<A*>(static_cast<void*>(p)), (5.2.10p7) so both your questions are equivalent.

For standard-layout classes, the address of the struct/class is the same as the address of its first non-static member (9.2p19). And static_cast to/from void* will preserve the address (5.2.9p13), meaning the result will be valid.

If the classes were not standard-layout, you could not rely on this behavior.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...