+ 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?
3 ответов
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)
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.
- 1
Perhaps it's because of the reference operator you use in second line with the string character type instead of using the val