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

c++ - typeid for polymorphic types

I expected this code to print 'Same 1' and 'Same2', but it prints only 'Same1':

#include <iostream>
#include <typeinfo>
using namespace std;

struct C{virtual ~C(){}};
struct D : C{};
int main(){
   D d;
   C c, &cr1 = d;
   if(typeid(cr1) == typeid(D)) cout << "Same1";
   if(typeid(&cr1) == typeid(D*)) cout << "Same2";
}

Both §5.2.8/2 and §5.3.1/3 seem to suggest to me that 'Same2' should be printed.

What and where is the catch?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Pointers aren't polymorphic types. They don't have virtual members. In fact, they have no members whatsoever. They also cannot derive from other types, nor be used as base classes. Hence, the static and dynamic type of a T* is always T*.

In your "Same2" line, you're comparing the typeid of a pointer, not the pointed-to object. The compiler therefore only looks at the static types C* and D*. They're obviously not the same, and must have distinct type_info objects.


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

...