簡體   English   中英

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

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

如果我調用typeid並檢索返回的type_info的地址:

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

typeid返回的 object 的生命周期是多少,指向該 object 的指針將保持多長時間有效?

無論實現如何實現它們, typeid表達式的結果都是左值,並且這些左值引用的對象的生命周期必須持續到程序結束。

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

typeid表達式的結果是一個左值 [...] 左值引用的 object 的生命周期延伸到程序的末尾。

從 C++ 2003 標准的 5.2.8.1 開始:

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 的生命周期延長到程序的末尾 未指定在程序末尾是否為 type_info object 調用析構函數。

它的生命周期是程序的持續時間。 而且無論你寫多少次typeid(x) ,它每次都會返回相同的type_info object ,對於相同的類型。

那是,

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

引用xinfoyinfo都引用相同的 object。 所以嘗試打印地址來驗證它:

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

Output:

0x80489c0
0x80489c0

注意:對於您的運行,地址可能與上述不同,但無論是什么,都將是相同的!

演示: http://www.ideone.com/jO4CO

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM