2

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?

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
wojcienty
  • 313
  • 1
  • 4
  • 14
  • 2
    That something could be possible does not mean it should be allowed. – Nicol Bolas Apr 25 '19 at 18:39
  • Ok, i get it. But why one is allowed, and other is not? Why we can do rvalue assignment to const reference, and can't do to non const reference? – wojcienty Apr 25 '19 at 18:42
  • "So why there is problem, with assignment to non const reference?" because language does not allow that. But you put it wrong, there would be a problem if you allow temporary to bind to lvalue reference, not the other way around. And MS has pesky extention that actually allows that and it does not make any good. – Slava Apr 25 '19 at 18:45

0 Answers0