typeid 运算符返回的对象的生命周期是多少?
如果我调用 typeid
并检索返回的 type_info
的地址:
const type_info* info = &( typeid( Something ) );
typeid
返回的对象的生命周期是多少以及指向该对象的指针将持续多长时间对象仍然有效吗?
If I call typeid
and retrieve the address of returned type_info
:
const type_info* info = &( typeid( Something ) );
what's the lifetime of the object returned by typeid
and how long will the pointer to that object remain valid?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
无论实现如何实现它们,
typeid
表达式的结果都是左值,并且这些左值引用的对象的生命周期必须持续到程序结束。来自 ISO/IEC 14882:2003 5.2.8 [expr.typeid]:
However the implementation implements them, the results of
typeid
expressions are lvalues and the lifetime of the objects that those lvalues refer to must last until the end of the program.From ISO/IEC 14882:2003 5.2.8 [expr.typeid]:
从C++ 2003标准的5.2.8.1开始:
From 5.2.8.1 of C++ 2003 standard:
它的生命周期就是程序的持续时间。无论您编写多少次
typeid(x)
,它每次都会返回相同的type_info
对象,且类型相同。也就是说,
引用
xinfo
和yinfo
都引用同一个对象。因此,尝试打印地址来验证它:输出:
注意:对于您的运行,地址可能与上面的不同,但无论它是什么,它都会是相同的!
演示:http://www.ideone.com/jO4CO
Its lifetime is the duration of the program. And no matter how many times you write
typeid(x)
, it will return the sametype_info
object everytime, for same type.That is,
The references
xinfo
andyinfo
both refer to the same object. So try printing the address to verify it:Output:
Note: for your run, the address might be different from the above, but whatever it is, it will be same!
Demo : http://www.ideone.com/jO4CO