+ 1

Difference between const and non-const reference in c++

Why does the first line compile and second doesn't? 1 - const std::string& val = "Hello"; Versus 2 - std::string& val = "Hello"; I can even retrieve the value later from the first val variable. Can someone explain me why?

23rd May 2022, 11:39 PM
Victor Cortes
Victor Cortes - avatar
3 Answers
0
Guys I've searched about this problem and got a precise answear: The literal "Hello" value is a rvalue (temporary value that expires after the line ends). If we declare the val as std::string& we are creating a reference to a value already stored in memory, ie an lvalue (a non-temporary value stored in memory). And that is why the sentence #2 does not work! Suprisingly, when we declare the val as a const reference, we can now store a rvalue as well, extending the lifecycle of the temp value. So: std::string& can point only to a non temp lvalue const std::string& can point to a lvalue, making a const reference to that; can point to a const lvalue; can point to a rvalue, making a const reference to that and extending the lifecycle (the value will be descarted after the scope end instead of after the line ends)
25th May 2022, 8:44 AM
Victor Cortes
Victor Cortes - avatar
0
If you are asking why this code doesn't work : const string& val = "hello" string& val = "hello" the answer is you are trying to redeclare the same variable (val) with conflicting definition. first you are declaring it as const ref then you are redeclaring as non-const reference. But if you are asking why this doesn't work: string& val = "Hello" It's because, string literals("Hello" in this case) are immutable(const), and what you are trying here is assigning const rvalue to non-const lvalue reference. Hence complier will throw error. "Cannot bind const rvalue to non-const lvalue reference" something like this. Suppose, If you could do it, later you could do something like val[0] = 'B' which means you could have changed the string literal "Hello" to "Bello" which is impossible because string literals are immutable. So you have to declare it as a const reference, which means you provide a guarantee to compiler that you will not change it later.
24th May 2022, 1:49 PM
Vinit Sonawane
Vinit Sonawane - avatar
- 1
Perhaps it's because of the reference operator you use in second line with the string character type instead of using the val
24th May 2022, 6:48 AM
Zaim Ali šŸ”„šŸ¤Ÿ
Zaim Ali šŸ”„šŸ¤Ÿ - avatar