Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: what are free-standing references used for?

Tags:

c++

reference

In which situation would you want to define a reference to some piece of memory?

For example:

const int & r = 8; 

as opposed to simply writing:

int r = 8;
like image 936
oli Avatar asked May 18 '14 16:05

oli


2 Answers

It is useful to replace a long expression to an object by a shorter reference and make the code more readable. For example:

const int &SphereRadius = Configuration::getInstance()->sphere->radius;

Whenever the configuration changes simultaneously (e.g. in another thread), your reference is updated.

The code you have shown is just a simple possibility of a greater tool. Your example in many cases is meaningless as you understood it before. The main goal of these kind of references is aliasing an object.

  • Passing objects by reference to a function and the ability to modify the referring object without the confusions of pointers.

  • Using them in ranged-based loops to modify the iterating item in a container.

  • Shortening an expression by a simpler one in some cases. and more... .

like image 94
masoud Avatar answered Nov 06 '22 11:11

masoud


You cannot bind a non-const reference to a rvalue, i.e. cannot "refer" to something that can not appear on the left hand side of an assignment operator (like a temporary object). The main reason is that when the temp gets destroyed, you end up with a dangling reference, and C++ does not allow this. Your code won't compile.

Funny though, you can bind a temp to a const reference, and this will prolong temp's lifetime, i.e.

const Foo& ref = Foo(); // creates a temporary Foo, destructor is not invoked now

However the temporary is not being destroyed. See Does a const reference prolong the life of a temporary? However I wouldn't use this in my code, it is just a source of confusion for most of us.

like image 5
vsoftco Avatar answered Nov 06 '22 11:11

vsoftco