gpt4 book ai didi

c++ - 另一个 C++ 临时生命周期困惑

转载 作者:搜寻专家 更新时间:2023-10-31 02:20:21 25 4
gpt4 key购买 nike

在下面的代码片段中...存储对 Quote::toXML 返回的临时字符串的引用是否安全?在ToXML::s_成员变量,至少只要它与 << 一起使用只有运营商? IE。是子表达式 q.toXML 的结果活到下一个;

这里 w.r.t. 的完整表达是什么? q.toXML 的返回值.整个std::cout或调用 ToXML构造函数?

#include <iostream>
#include <string>

struct ToXML
{
ToXML(char const * const tag, std::string const & s) : tag_(tag), s_(s)
{
}

char const * tag_;
std::string const & s_;
};

std::ostream & operator << (std::ostream & os, ToXML const & v)
{
return os << "<" << v.tag_ << ">" << v.s_ << "</" << v.tag_ << ">";
}

struct Quote
{
std::string toXML() const
{
return "<Quote/>";
}
};

int main()
{
Quote q;
std::cout << ToXML("quote", q.toXML()) << std::endl;
return 0;
}

最佳答案

是的,它是安全的。

来自 [class.temp]:

There are two contexts in which temporaries are destroyed at a different point than the end of the full-expression. [...]

The second context is when a reference is bound to a temporary.117 The temporary to which the reference isbound or the temporary that is the complete object of a subobject to which the reference is bound persistsfor the lifetime of the reference except:
— A temporary object bound to a reference parameter in a function call (5.2.2) persists until the completionof the full-expression containing the call.

我们正处于那个要点。临时对象绑定(bind)到引用参数 (s) 并持续存在,直到包含调用的完整表达式完成。也就是说,它一直持续到

std::cout << ToXML("quote", q.toXML()) << std::endl;
// --- here ---------------------------------------^

由于它在整个使用过程中持续存在,因此非常安全。但是,一旦您执行以下操作:

ToXML x("quote", q.toXML());

你被悬空引用困住了,所以我会谨慎使用这种模式。

关于c++ - 另一个 C++ 临时生命周期困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32813694/

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