引用一个未命名的临时对象(生命周期)
Reference to an unnamed temporary object (life time)
在阅读了来自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;
}
相关文章:
- 在不复制临时对象的情况下延长其生存期
- 为什么当我们有常量引用时创建临时对象?
- 程序如何'remember'临时对象?
- 返回对临时对象的引用
- 防止临时对象文件访问 MSVC 中的磁盘
- 是否可以在C++中移动临时对象的属性?
- 通过引用传递临时对象
- 临时C++对象是否为左值?
- 临时对象:术语澄清
- 存储对(可能)临时对象的引用是否合法,只要引用不比对象存活?
- 临时对象有身份吗?
- 传递给构造函数的临时对象的C++生命周期
- 为什么我们可以非常量引用临时对象并延长其生命周期
- 临时对象的生命周期:嵌套函数调用中指向临时向量的迭代器
- 延长临时对象的生命周期
- 与const引用(方法链)相关联的临时对象的生命周期
- 在调用点参数处创建的临时对象的生命周期
- 列表初始化期间临时对象的生命周期
- 引用一个未命名的临时对象(生命周期)
- 临时对象的生命周期