2013-03-07 36 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