2013-03-07 26 views
3

ildjarn閱讀this answer後,我寫了下面的例子,它看起來像一個無名的臨時對象具有相同的續航時間作爲參考!引用一位不願透露姓名的臨時對象(生命週期)

  • 這怎麼可能?
  • 是否在C++標準中指定?
  • 哪個版本?

源代碼:

#include <iostream> //cout 
#include <sstream> //ostringstream 

int main() 
{ 
     std::ostringstream oss; 
     oss << 1234; 

     std::string const& str = oss.str(); 
     char  const* ptr = str.c_str(); 

     // Change the stream content 
     oss << "_more_stuff_"; 
     oss.str(""); //reset 
     oss << "Beginning"; 
     std::cout << oss.str() <<'\n'; 

     // Fill the call stack 
     // ... create many local variables, call functions... 

     // Change again the stream content 
     oss << "Again"; 
     oss.str(""); //reset 
     oss << "Next should be '1234': "; 
     std::cout << oss.str() <<'\n'; 

     // Check if the ptr is still unchanged 
     std::cout << ptr << std::endl; 
} 

執行:

> g++ --version 
g++ (GCC) 4.1.2 20080704 (Red Hat 4.1.2-54) 
Copyright (C) 2006 Free Software Foundation, Inc. 
This is free software; see the source for copying conditions. There is NO 
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 
> g++ main.cpp -O3 
> ./a.out 
Beginning 
Next should be '1234': 
1234 
+4

「const」引用延長了臨時對象的生命週期的事實應該在你的C++書中相當公開。 – 2013-03-07 09:41:48

+1

如果您只是嘗試在網頁上搜索您使用的短語,您應該可以找到答案:_臨時對象與其reference_具有相同的生存時間_ – 2013-03-07 09:48:16

+1

[臨時生命期]的可能重複(http://stackoverflow.com/questions/4214153/lifetime-of-temporaries)/看看我發現了什麼 – 2013-03-07 09:54:45

回答

9

這怎麼可能?

因爲標準是這樣說的,因爲它被認爲是有用的。 rvalue引用和const左值引用的臨時延伸的壽命:

[C++11: 12.2/5]:[..]到其中參考結合臨時或暫時這是一個子對象的完整的對象到該參考是結合仍然存在 用於參考的壽命,除了[..]

和詳盡的措詞在[C++11: 8.5.3/5]要求,我們將不結合的臨時到非const左值的引用。


是它在C++標準中規定的? 哪個版本?

是的。他們全部。

6

臨時結合到const引用增加了臨時的壽命直到恆定的基準的壽命。

良好閱讀:

GotW #88: A Candidate For the 「Most Important const」


是的,它從時間參考C++標準被指定進行了介紹。
所以,如果你想知道這是否是C++ 11的功能,不,它不是。它已經存在於C++ 03中。

3

Lightness Races in Orbit是對的。我認爲這個例子會更簡潔。

#include <iostream> //cout 
#include <string> 

int main() 
{ 
    using namespace std; 
    int a = 123; 
    int b = 123; 
// int  & a_b = a + b; // error! 
    int const & a_b = a + b; 
    cout<<"hello world!"<<endl; 
    cout<<a_b<<endl; 
} 
+0

是的!我沒有想到這個!謝謝 ;-) – olibre 2013-03-07 15:01:58