在阅读了来自ildjarn的回答后,我编写了以下示例,它看起来像一个未命名的临时对象与其引用具有相同的生命周期!
- 这怎么可能?
- 是否在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
这怎么可能?
因为标准这么说,因为它被认为是有用的。右值引用和const
左值引用延长临时对象的生存期:
[C++11: 12.2/5]:
[…]引用被绑定到的临时对象或引用被绑定到的子对象的完整对象的临时对象持续存在在引用的生命周期内,除了[..]
和[C++11: 8.5.3/5]
中详尽的措辞要求我们不能将临时绑定到非const
左值引用。
是否在c++标准中指定?哪个版本?
是的。
与const引用的临时绑定使临时对象的生存期增加到常量引用的生存期。
优秀阅读:
gotw# 88:"最重要的const"候选
是的,从引入引用时起,它就在c++标准中指定了。
所以如果你想知道这是否是c++ 11的特性,不,它不是。它在c++ 03中已经存在了。
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;
}