This is the code from c++ primer:
string::size_type findChar(const string &s, char c, string::size_type & occurs){
auto ret = s.size();
occurs = 0;
for (decltype(ret) i = 0; i != s.size(); ++i){
if (s[i] == c){
if (ret == s.size())
ret = i;
occurs++;
}
}
return ret;
}
int main () {
string::size_type ctr;
cout << findChar("hello, world!", 'o', ctr);
}
An error happened after removing const
from const string &s
.
error: cannot bind non-const lvalue reference of type 'std::__cxx11::string&' {aka 'std::__cxx11::basic_string&'} to an rvalue of type 'std::__cxx11::string' {aka 'std::__cxx11::basic_string'} cout << findChar("hello, world!", 'o', ctr);
I wonder, in this case, what behaviors of compiler does the const
keyword change? Thanks for helping me.
const
means "this value can be manipulated" which may not be permitted depending on how the argument is provided. – tadman