简体   繁体   English

c + +:返回对临时的引用

[英]c++ : returning reference to temporary

I have made this c++ code : 我做了这个C ++代码:

std::string const &     Operand::toString() const
{
  std::ostringstream    convert;
  convert << this->value;
  return convert.str();
}

The compiler tells me : returning reference to temporary 编译器告诉我: returning reference to temporary

Am I forced to put convert.str() in my Operand class ? 我是否必须将convert.str()放入我的Operand类中?

EDIT : It's for a school exercise, I can't change the prototype 编辑:这是一次学校练习,我无法更改原型

convert.str();

this returns an std::string object which will be destroyed after Operand::toString() returns. 这将返回一个std::string对象,该对象将在Operand::toString()返回之后销毁。 Thus this is temporary variable with lifetime limited to scope of this function. 因此,这是临时变量,其生存期限于此功能的范围。 You should return just the string itself, by value: 您应该只按值返回string本身:

std::string Operand::toString() const
{
  std::ostringstream    convert;
  convert << this->value;
  return convert.str();
}

or: 要么:

const std::string Operand::toString() const
{
  std::ostringstream    convert;
  convert << this->value;
  return convert.str();
}

Just change the function to return a std::string instead of a std::string const & . 只需更改函数以返回std::string而不是std::string const & You want to return by value here. 您想在此处按值返回。

Just remove the & and const 只需删除&和const

ie

std::string Operand::toString() const
{
  std::ostringstream    convert;
  convert << this->value;
  return convert.str();
}

If you can't change the prototype - it must return reference instead the string itself - you have to keep the string somewhere and return reference to it. 如果您不能更改原型-它必须返回引用而不是字符串本身-您必须将字符串保留在某个地方并返回对其的引用。 Maybe create a static string, assign convert.str() into it and return reference to this static string. 也许创建一个静态字符串,在其中分配convert.str()并返回对该静态字符串的引用。

std::string const & Operand::toString() const
{
  static std::string s;
  std::ostringstream convert;
  convert << this->value;
  s = convert.str();
  return s;
}

Another solution is recommended in comment by David Schwartz (at different answer), but it depends if you can add that member string to Operand . David Schwartz在评论中建议使用另一种解决方案(答案不同),但这取决于您是否可以将该成员字符串添加到Operand

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM