What is the lifetime of the object returned by the typeid operator?

If I call typeid and get the address of the returned type_info :

 const type_info* info = &( typeid( Something ) ); 

what is the lifetime of the object returned by typeid , and how long will the pointer to this object remain?

+4
source share
3 answers

However, the implementation implements them, the results of typeid expressions are lvalues, and the lifetime of the objects to which these lvalues โ€‹โ€‹belong must continue until the end of the program.

From ISO / IEC 14882: 2003 5.2.8 [expr.typeid]:

The result of the typeid expression is lvalue [...] The lifetime of the object referenced by lvalue continues to the end of the program.

+10
source

From 5.2.8.1 of the C ++ 2003 standard:

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

+5
source

His 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 every time, for the same type.

I.e

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

The xinfo and yinfo both refer to the same object. So try to print the address to check it:

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

Output:

 0x80489c0 0x80489c0 

Note: for your run, the address may differ from the above, but whatever it is, it will be the same!

Demo: http://www.ideone.com/jO4CO

+2
source

All Articles