看到一段code:
#if defined _CPPRTTI
const char* errorType = typeid(SomeClass).name();
#else
const char* errorType = "Unknown";
#endif
[_CPPRTTI ]
http://msdn.microsoft.com/en-us/library/b0084kay(v=vs.80).aspx
_CPPRTTI | Defined for code compiled with /GR (Enable Run-Time Type Information). |
[/GR]
http://msdn.microsoft.com/en-us/library/we6hfdy0(v=vs.80).aspx
Adds code to check object types at run time. When /GR is on, the compiler defines the _CPPRTTI preprocessor macro. In Visual C++ 2005, /GR is on by default. /GR- disables run-time type information. Use /GR if your code uses dynamic_cast Operator or typeid. /GR does, however, cause the .rdata sections of your image to increase in size. If your code does not use dynamic_cast or typeid, using /GR- may produce a smaller image.
[typeid]
typeid 运算符:获得一个类型或者对象的运行时信息。typeid(SomeClass) 返回类型为const type_info& 的对象。其中 const char* type_info::name() 得到该类型的名字。
在VS上,输出class MyOwnClass 这样可读的,原生的名字。
在g++上,输出的是经过name-mangling后的类型名,和类型原名差不多,比如nmMyOwnClass12w这样的,人眼可读。
所以在进行字符串比较时,不要跟预先定义好的字符串比较,要跟typeid().name() 比较。
//Wrong
if (className == "MyClass")
//Correct
if (className == typeid(MyClass).name())