Why can't I use the << << operator in the return statement?

For instance:

 std::stringstream formatMemUsage(...) { std::stringstream ss ... ... return ss << "MB"; // Error here } 

leads to an error no suitable user-defined conversion from "std::basic_ostream<char, std::char_traits<char>>" to "std::stringstream" exists .

I can split the return statement into 2 ss << "MB"; return ss; statements ss << "MB"; return ss; ss << "MB"; return ss; , and the error will disappear - why?

(using MSVC ++ 2010)

+4
source share
2 answers

Because you are returning the last processed statement. Think about what this actually does:

 return ss << "MB"; 

It is equivalent to:

 return operator<<(ss, "MB"); 

The operator<< return type in this case, as you saw, as you saw, std::ostream& is not a std::stringstream as you wanted.

+8
source

There are several issues. First, as Yushi points out, the type of the ss << "MB" expression is std::ostream& , not std::stringstream , and there is no implicit conversion from std::ostream to std::stringstream . Secondly, streams cannot be copied, so you can never return a std::stringstream (which will require a copy). And also you cannot just change the return value to std::ostream& , because this will return a reference to the local variable; ss will be destroyed 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.

+1
source

Source: https://habr.com/ru/post/1480069/


All Articles