引用未命名的临时对象(life time) [英] Reference to an unnamed temporary object (life time)
问题描述
在阅读此回答之后,ildjarn ,我写了以下示例,它看起来像一个未命名的临时对象具有与其参考相同的生命时间!
After reading this answer from ildjarn, I wrote the following example, and it looks like an unnamed temporary object has the same life time as its reference!
- 这是怎么可能的?
- 是否在C ++标准中指定?
- 哪个版本?
源代码: >
Source code:
#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
推荐答案
如何实现?
How come this is possible?
因为标准说,所以,因为它被认为是有用的。 rvalue引用和 const
lvalue引用扩展临时表的生命周期:
Because the standard says so, because it's deemed useful. rvalue references and const
lvalue references extend the lifetime of temporaries:
[C ++ 11:12.2 / 5]:
[..] 引用绑定的临时或临时,子引用绑定的子对象将在引用的生命周期中保持
,除了 [..]
[C++11: 12.2/5]:
[..] The temporary to which the reference is bound or the temporary that is the complete object of a subobject to which the reference is bound persists for the lifetime of the reference, except [..]
$ b $在 [C ++ 11:8.5.3 / 5]
中要求我们不将临时绑定到非 - const
lvalue references。
and exhaustive wording in [C++11: 8.5.3/5]
requires that we shall not bind temporaries to non-const
lvalue references.
?
哪个版本?
Is it specified in the C++ standard? Which version?
是的。所有人。
这篇关于引用未命名的临时对象(life time)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!