What's the lifetime of the object returned by typeid operator?

回眸只為那壹抹淺笑 提交于 2019-12-12 11:16:58

问题


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?


回答1:


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]:

The result of a typeid expression is an lvalue [...] The lifetime of the object referred to by the lvalue extends to the end of the program.




回答2:


From 5.2.8.1 of C++ 2003 standard:

The result of a typeid expression is an lvalue of static type const std::type_info (18.5.1) and dynamic type const std::type_info or const name where name is an implementation-defined class derived from std::type_info which preserves the behavior described in 18.5.1.61) The lifetime of the object referred to by the lvalue extends to the end of the program. Whether or not the destructor is called for the type_info object at the end of the program is unspecified.




回答3:


Its lifetime is the duration of the program. And no matter how many times you write typeid(x), it will return the same type_info object everytime, for same type.

That is,

 T x, y;
 const type_info & xinfo = typeid(x);
 const type_info & yinfo = typeid(y);

The references xinfo and yinfo both refer to the same object. So try printing the address to verify it:

 cout << &xinfo << endl; //printing the address
 cout << &yinfo << endl; //printing the address

Output:

0x80489c0
0x80489c0

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



来源:https://stackoverflow.com/questions/7024818/whats-the-lifetime-of-the-object-returned-by-typeid-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!