What's the lifetime of the object returned by typeid operator?
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 r开发者_StackOverflowemain valid?
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.
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.
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
精彩评论