Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can I not use the "<<" operator in a return statement?

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)

like image 414
mchen Avatar asked Jan 14 '23 10:01

mchen


2 Answers

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.

like image 86
Yuushi Avatar answered Jan 18 '23 00:01

Yuushi


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.

like image 45
James Kanze Avatar answered Jan 17 '23 23:01

James Kanze