Reputation: 2019
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
Upvotes: 0
Views: 4858
Reputation: 29724
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();
}
Upvotes: 6
Reputation: 25181
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
.
Upvotes: 0
Reputation: 59997
Just remove the &
and const
i.e.
std::string Operand::toString() const
{
std::ostringstream convert;
convert << this->value;
return convert.str();
}
Upvotes: 1
Reputation: 182753
Just change the function to return a std::string
instead of a std::string const &
. You want to return by value here.
Upvotes: 4