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
461 views
in Technique[技术] by (71.8m points)

to get the real type information of a pointer in c++

class myclass1 {
public:
    virtual ~myclass1() {

    }
};

class myclass2 : public myclass1 {

};

int main() {

    myclass1 obj1;
    myclass2 obj2;

    myclass1 *p1 = &obj2;
    myclass2 *p2 = static_cast<myclass2 *>(&obj1);

    if( p1 && p2){
        cout << typeid(p1).name() << endl;
        cout << typeid(p2).name() << endl;
    }
}

The output is as below:

P8myclass1
P8myclass2

Process finished with exit code 0

cion capture

The code has two classes, I tried to use two types pointer to point to the other type. From base class to its children is totally ok while the other way around should not work ("myclass2 *p2 = static_cast<myclass2 *>(&obj1);"). If I use "dynamic_cast", the casted pointer will be null. But if I use "static_cast", the cast seems successful and the type is "myclass2" when I use typeid method.

When I am in debug mode in Clion, it seems the debugger knows the real type of the pointer, as shown in the image. It knows the type of p1 is "myclass2" and type of p2 is "myclass1". What is the magic of it?

obj1 = {myclass1} 
obj2 = {myclass2} 
p1 = {myclass2 * | 0x7ffeec114a08} 0x00007ffeec114a08
p2 = {myclass1 * | 0x7ffeec114a10} 0x00007ffeec114a10
question from:https://stackoverflow.com/questions/65947587/to-get-the-real-type-information-of-a-pointer-in-c

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

1 Answer

0 votes
by (71.8m points)

typeid(p1) will give you the type of the pointer p1, which will always be myclass1 * (the string P8myclass1 is the mangled name for the type myclass1 *). If you want the type of the pointed-at object, you want typeid(*p1), which should be myclass2 in this case.

With p2, typeid(p2) will be myclass2 *, while typeid(*p2) gives undefined behavior -- you can't safely dereference a pointer after a static cast to the wrong type. It is likely that you'll get myclass1, but not certain -- you might get a crash.

The debugger is essentially doing that with extra knowledge and protection to avoid bad misbehavior from the undefined behavior.


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

2.1m questions

2.1m answers

60 comments

57.0k users

...