[英]Reference to an unnamed temporary object (life time)
从ildjarn读完这个答案 之后 ,我编写了以下示例,它看起来像一个未命名的临时对象与其引用具有相同的生命周期!
源代码:
#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
怎么可能呢?
因为标准这样说,因为它被认为是有用的。 右值引用和const
左值引用延长了临时值的生命周期:
[C++11: 12.2/5]:
[..]引用绑定的临时值或作为引用绑定的子对象的完整对象的临时值在引用的生命周期内持续存在, [[ ..]
和详尽的措词在[C++11: 8.5.3/5]
需要,我们将不结合的临时到非const
左值的引用。
它是在C ++标准中指定的吗? 哪个版本?
是。 他们全部。
临时绑定到const引用会增加临时值的生命周期,直到常量引用的生命周期为止。
好读:
是的,从引入时间引用开始就在C ++标准中指定。
因此,如果您想知道这是否是C ++ 11功能,不是不是。 它已经存在于C ++ 03中。
轨道中的轻盈竞赛是正确的。 我认为这个例子会更简洁。
#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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.