我是否正确阅读了 5.2.8.3 中的标准:...如果
expression 是一个类类型,该类应该是完全定义的。
如果类型不是“完全定义的”,是否意味着下面的程序是未定义的?
foo.cpp:
struct foo
{
virtual void a(){}
};
struct bar : foo
{
virtual void a(){}
};
bar abar;
foo& get_some_foo()
{
return abar;
}
主要.cpp:
#include <iostream>
#include <typeinfo>
struct foo;
foo& get_some_foo();
int main()
{
foo& a_ref_foo(get_some_foo());
std::cout << "a_ref_foo typeid name: " << typeid(a_ref_foo).name() << std::endl;
return 0;
}
MSVC10 输出:`a_ref_foo typeid name: struct foo'
最佳答案
当我编译你的代码时:
g++ foo.cpp main.cpp -o main
我得到:
main.cpp: In function ‘int main()’:
main.cpp:12:52: error: invalid use of incomplete type ‘struct foo’
main.cpp:4:8: error: forward declaration of ‘struct foo’
这与我对标准的解释一致,您不能将 typeid
应用于不完整的类型 — 而 a_ref_foo
是不完整的类型,因为完整的定义foo
类型的是不可见的。 main.cpp
(包含我添加的行)格式错误,需要进行诊断。
更新:
我已经用 Visual Studio 2010 Express 重现了这个问题。即使禁用了语言扩展,这个微不足道的程序:
#include <typeinfo>
struct foo;
int main()
{
typeid (foo);
return 0;
}
编译时没有诊断信息。使用 gcc 4.7,我得到:
main.cpp: In function ‘int main()’:
main.cpp:7:14: error: invalid use of incomplete type ‘struct foo’
main.cpp:3:8: error: forward declaration of ‘struct foo’
同样的规则:
If the type of the expression is a class type, the class shall be completely-defined.
出现在 ISO C++ 标准的 1998、2003 和 2012 版本中。
看起来像是 Visual Studio 中的错误。 (如果有人想将此报告给 Microsoft,请继续。)
关于c++ - 是否在前向声明的类型未定义行为上使用 typeid?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11321007/