简体   繁体   中英

c++ : returning reference to temporary

I have made this c++ code :

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

The compiler tells me : returning reference to temporary

Am I forced to put convert.str() in my Operand class ?

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. Thus this is temporary variable with lifetime limited to scope of this function. You should return just the string itself, by value:

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 & . You want to return by value here.

Just remove the & and 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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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