N
N
Nexeon2016-03-18 15:34:18
C++ / C#
Nexeon, 2016-03-18 15:34:18

How is an rvalue reference different from an lvalue reference?

Good afternoon. If I'm not mistaken, then an lvalue reference &rcan refer to the memory address of a named object (variable). So, an rvalue reference &&rris the same as an lvalue reference, only it can refer to a temporary object? (for example, a literal 5)
I show by example that they are similar:

int x = 5;
int &r = x; //lvalue-ссылка
r = 10;
cout <<  x; //в консоли: 10

//другой пример:
int x = 5;
int &&rr = move(x); //rvalue-ссылка
rr = 10;
cout <<  x; //в консоли: 10

I show by example what can refer to a temporary object:
int x = 5;
inr &r = x; //work
int &r = 10; //nope

int &&rr = x; //nope
int &&rr = move(x); //work
int &&rr = 10; //work

Can anyone explain? If they work almost the same, then what is the benefit of using rvalue references in move semantics. The topic is very difficult for me. I can't understand the concept..

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Stanislav Makarov, 2016-03-18
@MrNexeon

then what is the benefit of using rvalue references in move semantics

The fact that they allow you to distinguish between temporary objects, from which you can steal something useful, from permanent ones, with which it is better not to do this. Persistent objects will continue to be copied by copy constructors. But for temporary ones, the move constructor will be selected, if one is defined.
The use of std::move is the ability to name some language-constant object (for example, an ordinary local variable) as a temporary one, when you are sure that its contents are not needed further in the code. For it, the destructor will still be called (i.e., an object that falls under the move-semantics is NOT considered destroyed after that), but after the move procedure, the object is considered to be in some indefinite ("empty"), but valid state.

D
Denis Zagaevsky, 2016-03-18
@zagayevskiy

Detailed description: https://habrahabr.ru/post/226229/

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question