在向前声明的类型上使用typeid的行为未定义吗? [英] Is using typeid on a forward declared type undefined behavior?

查看:42
本文介绍了在向前声明的类型上使用typeid的行为未定义吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 5.2.8.3中正确阅读了标准:...表达式是一个类类型,则该类应该是完全定义的.如果类型不是完全定义",是否意味着以下程序是未定义的?

Am I reading the standard correctly in 5.2.8.3: ... If the type of the expression is a class type, the class shall be completely-defined. If the type is not "completely-defined" does that mean the following program is undefined?

foo.cpp:

struct foo
{
  virtual void a(){}
};

struct bar : foo
{
  virtual void a(){}
};

bar abar;

foo& get_some_foo()
{
  return abar;
}

main.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名称:struct foo'

MSVC10 outputs: `a_ref_foo typeid name: struct foo'

推荐答案

当我使用以下代码编译您的代码时:

When I compile your code with:

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 (加上我添加的行)格式不正确,并且需要进行诊断.

That agrees with my interpretation of the standard, that you can't apply typeid to an incomplete type — and a_ref_foo is of an incomplete type, since the full definition of the type foo is not visible. main.cpp (with the lines I added) is ill-formed, and a diagnostic is required.

更新:

我已复制了Visual Studio 2010 Express的问题.即使禁用了语言扩展,该微不足道的程序:

I've reproduced the issue with Visual Studio 2010 Express. Even with language extensions disabled, this trivial program:

#include <typeinfo>

struct foo;

int main()
{
  typeid (foo);
  return 0;
}

编译,无诊断消息.使用gcc 4.7,我得到:

compiled with no diagnostic messages. With gcc 4.7, I get:

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版本中.

appears in the 1998, 2003, and 2012 versions of the ISO C++ standard.

看起来像Visual Studio中的错误.(如果有人想向微软报告,请继续.)

Looks like a bug in Visual Studio. (If somebody would like to report this to Microsoft, go ahead.)

这篇关于在向前声明的类型上使用typeid的行为未定义吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆