c++11 - Reference parameter (&) with and without const in C++ -


so writing program yesterday, , encountered problem when use reference without const, it'll error whenever tried call function later. example:

bool is_vowel(const string& s) //ok; bool is_vowel(string& s) //error! {     if (s == "a" || s == "a") return true;     if (s == "e" || s == "e") return true;     if (s == "i" || s == "i") return true;     if (s == "o" || s == "o") return true;     if (s == "u" || s == "u") return true;     if (s == "y" || s == "y") return true;      return false; } 

and considering following calls function: (for simplicity, i've cut out huge chunk of original code, don't focus on logic here)

int fri_syllables(const string& s) {     int syllables = 0;      (int n = 0; n < s.length(); n++)         if (is_vowel(s.substr(n, 1)))             syllables ++; }  return syllables; 

}

so when use function, line calls is_vowel when don't use const return compile-time error saying "no matching function call 'is_vowel'".

i know why references const here works; don't understand why 1 without doesn't.

and thing makes me more confusing in fri_syllables function, references work , without const. considering part of code in main function calls function:

int main() {     //rest of code      int syllables = 0;     (int = 0; < words.size(); i++)         syllables += fri_syllables(words[i]);      //rest of code } 

this won't return error whether use int fri_syllables(const string& s) or int fri_syllables(string& s). why differences? why references without const work , others don't?

a non-const lvalue reference variable binds lvalues, not rvalues. contrast, const lvalue reference binds both lvalues , rvalues.

since result of s.substr(n, 1) rvalue (a "temporary value"), cannot bind non-constant lvalue reference.

the reasoning behind language design choice purpose of non-constant lvalue reference allow change object that's being referred to, when object temporary, changes lost immediately, never have intended.


Comments

Popular posts from this blog

javascript - jquery or ashx not working -

opencv - DataType<cv::detail::deriv_type>::depth what is it used for -

python 3.x - Mapping specific letters onto a list of words -