gpt4 book ai didi

c++ - 引用未命名的临时对象(生命周期)

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:56:46 29 4
gpt4 key购买 nike

看完this answer来自 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

最佳答案

How come this is possible?

因为标准是这么说的,因为它被认为是有用的。右值引用和 const 左值引用延长了临时对象的生命周期:

[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 [..]

[C++11: 8.5.3/5] 中详尽的措辞要求我们不得将临时对象绑定(bind)到非const 左值引用。


Is it specified in the C++ standard? Which version?

是的。所有这些。

关于c++ - 引用未命名的临时对象(生命周期),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15267676/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com