在下面的代码片段中...存储对 Quote::toXML
返回的临时字符串的引用是否安全?在ToXML::s_
成员变量,至少只要与 <<
一起使用即可仅运营商? IE。是子表达式 q.toXML
的结果活着直到下一个;
?
这里的完整表达是什么? 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 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:
— A temporary object bound to a reference parameter in a function call (5.2.2) persists until the completion of 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/