i recently try to fully understand rvalue and lvalue distinction and what it means in c++, and i stopped on const
reference assignment by rvalue.
What i mean is.
When we talk about rvalues we think about some anonymous value, that we cannot reference (except &&
operator, which i don't mention this time, because its not relevant in this case. Correct me if i'm wrong.).
And as we cannot reference it, there is no possibility to make assignment of it to reference variable, e.g. int& a = 5;
, and i get it.
But there is a case, when we can do it, and it is when reference is const, e.g. const int& a = 5;
I tried to understand why is it that way, and i cannot truly get why is that possible. Why it can be referenced, by only when we can't change this reference? For example. As i tried to check by gcc dissasembly, how its done, i found out, that compiler make some space on stack, and then put this rvalue there. Exactly like this:
C++:
int main() {
const int &a = 7;
}
Assembly:
main:
push rbp
mov rbp, rsp
mov eax, 7
mov DWORD PTR [rbp-12], eax
lea rax, [rbp-12]
mov QWORD PTR [rbp-8], rax
mov eax, 0
pop rbp
ret
I see clearly that there is value, that can we reference to and modify. So why there is problem, with assignment to non const reference? Can't we use the same assembly for it? (I tried it with string reference as well, and there is no difference, except some constructors and etc. calling. Pointer still on stack; Of course i understand, that machine code implementation of c++ is extremely below c++, but i tried to find a reason for non const reference problem)
Is it some logic consequence of abstractions that c++ made, and i should take it as 'it just works like that, because of c++ concepts', or there is some other explanation, maybe more clear for low level understanding?