2
在下面的代码片段中,至少只要它与<<
运算符一起使用,是否可以安全地将Quote::toXML
返回的临时字符串的引用存储在ToXML::s_
成员变量中?即是子表达式q.toXML
直到下一个;
的结果?另一个C++临时生命周期混淆
什么是这里完整的表达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;
}
看看:http://stackoverflow.com/questions/2822243/store-return-value-of-function-in-reference-c 根据这些信息,由于你的函数采用const引用它看起来OK 。 –