Reputation: 1125
I have following function
void myfun(std::string &str);
and I'm calling this functionas follows:
stringstream temp("");
temp << "some string data" ;
myfun(temp.str());
but I'm getting following error:
error: no matching function for call to ‘myfun(std::basic_stringstream<char>::__string_type)’
and
no known conversion for argument 1 from ‘std::basic_stringstream<char>::__string_type {aka std::basic_string<char>}’ to ‘std::string& {aka std::basic_string<char>&}’
How can I pass this string by reference?
Upvotes: 1
Views: 1715
Reputation: 258608
str
returns by value, i.e. a copy of the internal string in temp
. You can't pass a copy by non-const
reference.
You can modify the function signature to:
void myfun(const std::string &str);
Upvotes: 2
Reputation: 55887
Why you need this? Why myfun
receives reference, but not const
? std::stringstream::str
returns std::string
, that is temporary object and cannot be binded to lvalue-reference
.
You can send copy to function
std::string tmp = temp.str();
fun(tmp);
If you don't want to modify str
in function fun
you can rewrite it's signature to
void myfun(const std::string& str)
Upvotes: 4