Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is it allowed to pass R-Values by const reference but not by normal reference?

The following program

void display(const int& a) {     cout << a ; } 

will work if called with a literal like this

display(5); 

but without the const it won't work.

So how can a const reference keep pointing to an R-Value (anonymous variable)?

like image 584
Mekacher Anis Avatar asked Mar 19 '16 14:03

Mekacher Anis


People also ask

Can R values be const?

If you could pass an r-value by (non-const) reference, you could also be able to assign to it from inside the function. Therefore the rule that if r-values are to be passed by reference, this has to be a const reference.

Why can't you make a non-const reference to a literal?

A non-const reference cannot point to a literal. You cannot bind a literal to a reference to non-const (because modifying the value of a literal is not an operation that makes sense) and only l-values can be bound to references to non-const.

When should we use a const reference and why?

When we create our own copy constructor, we pass an object by reference and we generally pass it as a const reference. One reason for passing const reference is, we should use const in C++ wherever possible so that objects are not accidentally modified.

What are the differences between passing a parameter by reference and by constant reference?

The important difference is that when passing by const reference, no new object is created. In the function body, the parameter is effectively an alias for the object passed in. Because the reference is a const reference the function body cannot directly change the value of that object.


1 Answers

For your final question:

how can a const reference keep pointing to an R-Value (anonymous variable)

Here is the answer. The C++ language says that a local const reference prolongs the lifetime of temporary values until the end of the containing scope, but saving you the cost of a copy-construction (i.e. if you were to use an local variable instead).

like image 68
Tanz87 Avatar answered Oct 03 '22 16:10

Tanz87