What is the purpose of having a class member that is of type ref?

I have this code, but this is not a practical example.

Ref.

class Animal { int i; int& ref; public: Animal() : ref(i) { } }; 

Can someone provide an example of real life where ref is required as a member of a class so that I can better understand it?

+6
source share
3 answers

At any time when several objects of a class A all need to refer to one common instance of the same or any other class; for example, several People may have the same mother and / or father:

 class Person { private: Person &mother_; Person &father_; public: Person(Person &mother, Person &father) : mother_(mother), father_(father) {} // ... } 
+3
source

Of course: the whole purpose of the std::reference_wrapper<T> template std::reference_wrapper<T> is to link!

This has many uses. For example, you can pass it to the std::thread constructor (which always makes copies). You can also create reference wrapper containers.

Saving a link to something can also be useful when you want to wrap an output stream; you save the source stream as a link and add things to it (for example, this my answer can be improved by adding a link to the base stream to wrapper objects).

+1
source

This is basically the same as the const pointer. If you need a non-zero pointer to some other object, and this pointer will be assigned only during construction, you can use the link instead.

+1
source

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


All Articles