C ++: what are offline links used for?

In what situation do you want to define a link to some part of the memory?

For instance:

const int & r = 8; 

and not just write:

 int r = 8; 
+6
source share
2 answers

It is useful to replace a long expression with an object with a shorter link and make the code more readable. For instance:

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

Whenever the configuration changes at the same time (for example, in another thread), your link is updated.

The code you showed is just an easy opportunity for a larger tool. Your example in many cases is meaningless, as you understood before. The main purpose of these kinds of links is to overlay an object.

  • Passing objects by reference to a function and the ability to change the reference object without confusing pointers.

  • Using them in a range-based loop to modify an iterative element in a container.

  • Reduction of expression in simpler cases. and much more....

+10
source

You cannot bind a non-constant link to an rvalue, that is, you cannot β€œlink” to something that cannot appear on the left side of an assignment operator (for example, a temporary object). The main reason is that when temp is destroyed, you end up in a wrapped link, and C ++ does not allow this. Your code will not compile.

It's funny, however, that you can bind temp to a constant reference, and this will extend the lifetime of temp, i.e.

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

However, the temporary is not destroyed. See Does a reference to a constant contain a temporary service life? However, I would not use this in my code, it's just a source of confusion for most of us.

+5
source

Source: https://habr.com/ru/post/969471/


All Articles