c – 在多态对象上使用typeid时,是否必须定义它?

在多态对象上使用typeid时,我认为必须定义对象(而不仅仅是声明),因为typeid操作需要在运行时获取对象的信息.这是我的代码
#include <iostream>
#include <typeinfo>

class D {
    virtual ~D() {}
};
extern D d;

int main()
{
    std::cout << typeid(d).name() << std::endl;
    std::cout << sizeof(d) << std::endl;
}

使用clang 3.4,我收到链接错误

undefined reference to `d’

但是在g++ 4.8.1,它运作良好,我得到了结果:

1D
8

我的问题:

>哪一个是对的?
> g如何实现typeid?如何在没有定义的情况下从多态对象中获取信息?

解决方法

http://en.cppreference.com/w/cpp/language/typeid

a) If expression is a glvalue expression that identifies an object of a polymorphic type (that is,a class that declares or inherits at least one virtual function),the typeid expression evaluates the expression and then refers to the std::type_info object that represents the dynamic type of the expression. If the result of the evaluated expression is a null pointer,an exception of type std::bad_typeid or a type derived from std::bad_typeid is thrown.

听起来像clang 3.4是对的.

更新

标准说:

When typeid is applied to a glvalue expression whose type is a polymorphic class type (10.3),the result refers to a std::type_info object representing the type of the most derived object (1.8) (that is,the dynamic type) to which the glvalue refers. If the glvalue expression is obtained by applying the unary * operator to a pointer and the pointer is a null pointer value (4.10),the typeid expression throws the std::bad_typeid
exception (18.7.3).

它与cppreference.com使用的语言略有不同,但仍然指出clang 3.4是正确的.

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...