简体   繁体   English

typeid 运算符返回的 object 的生命周期是多少?

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

If I call typeid and retrieve the address of returned type_info :如果我调用typeid并检索返回的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? typeid返回的 object 的生命周期是多少,指向该 object 的指针将保持多长时间有效?

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.无论实现如何实现它们, typeid表达式的结果都是左值,并且这些左值引用的对象的生命周期必须持续到程序结束。

From ISO/IEC 14882:2003 5.2.8 [expr.typeid]:来自 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. typeid表达式的结果是一个左值 [...] 左值引用的 object 的生命周期延伸到程序的末尾。

From 5.2.8.1 of C++ 2003 standard:从 C++ 2003 标准的 5.2.8.1 开始:

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 . typeid 表达式的结果是 static 类型 const std::type_info (18.5.1) 和动态类型 const std::type_info 或 const name 的左值,其中 name 是实现定义的 class 派生自 std::type_info 18.5.1.61 中描述的行为)左值引用的 object 的生命周期延长到程序的末尾 Whether or not the destructor is called for the type_info object at the end of the program is unspecified.未指定在程序末尾是否为 type_info object 调用析构函数。

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.而且无论你写多少次typeid(x) ,它每次都会返回相同的type_info object ,对于相同的类型。

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.引用xinfoyinfo都引用相同的 object。 So try printing the address to verify it:所以尝试打印地址来验证它:

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

Output: 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演示: http://www.ideone.com/jO4CO

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM