user13052229
user13052229

Reputation:

Rvalue References in C++ with an easy example

Im trying to understand what exactly Rvalue References are. Everywhere I look they have examples to something called Perfect forwarding which sounds too complicated.

I just want a clear basic example of what Rvalue References are and see if they get used outside of the topics like Perfect forwarding.

I have read:

An lvalue is an expression that refers to a memory location and allows us to take the address of that memory location via the & operator. An rvalue is an expression that is not an lvalue

So is it correct to say:

An Rvalue Reference is a Reference to something that is not in the memory? Maybe it's in a register?

For example:

#include <iostream>

int main()
{
   int&& a = 50;  
   int b = 60;

  return 0;
}

50 is technically not in memory yet but a is a reference to it? is b any different than a?

Where else (which is easily explainable) can this be used?

Upvotes: 3

Views: 8394

Answers (1)

HolyBlackCat
HolyBlackCat

Reputation: 96246

First, whether or not something resides in the memory or in a register is not defined by the standard. You don't need to think about it. For you, all objects work as if they were in memory. Under the as-if rule, your compiler can put some of them into the registers, as long as it doesn't affect how your program works.

Yes, you can obtain addresses of lvalues (except bitfields) and not rvalues, but that's a language design choice rather than a technical limitation (most of the time it would make no sense, so it's not allowed). Value categories (lvalues vs rvalues) have nothing to do with how things are stored in memory.

Im trying to understand what exactly Rvalue References are

Rvalue references are similar to lvalue references. The primary difference is what you can initialize them with. Rvalue references must be initialized with rvalues, and lvalue references must be initialized with lvalues (as an exception, const lvalue references are allowed to bind to rvalues).

int&& a = 50; works because 50 is an int and a temporary object. (Usually "a temporary object" is a synonym for "an rvalue", but not always.)

This case is a bit tricky, because temporaries as normally destroyed at the end of full-expression (roughly, when the line of code they were created in finishes executing). But here, the lifetime of 50 is extended because it's bound to a reference.

is b any different than a?

int&& a = 50;  
int b = 60;

Because of the lifetime extension - no, they're equivalent. Maybe there's some obscure difference between them, but I can't think of any.

Upvotes: 7

Related Questions