For instance:
std::stringstream formatMemUsage(...) {
std::stringstream ss ...
...
return ss << "MB"; // Error here
}
results in the the error no suitable user-defined conversion from "std::basic_ostream<char, std::char_traits<char>>" to "std::stringstream" exists
.
I can separate the return statement into 2 statements ss << "MB"; return ss;
and the error disappears - why?
(Using MSVC++ 2010)
Because you are returning the last evaluated statement. Consider what this is actually doing:
return ss << "MB";
Is equivalent to:
return operator<<(ss, "MB");
The return type of operator<<
in this case is, as you've seen, std::ostream&
- not a std::stringstream
as you wanted.
There are several problems. The first is, as Yuushi points out,
that the type of the expression ss << "MB"
is std::ostream&
,
and not std::stringstream
, and there is no implicit conversion
from std::ostream
to std::stringstream
. The second is that
streams are not copiable, so there is no way you can ever
return a std::stringstream
(which would require a copy). And
you can't simply change the return value to std::ostream&
,
because that would result in returning a reference to a local
variable; ss
will be destructed at the end of the function.
What are you trying to achieve? Most of the time, just
returning a string (ss.str()
) would be a better solution.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With