Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When do I use references?

Tags:

c++

reference

My understanding of references is that they are an alias to an already-existing variable - they cannot be null. They are useful for function calls when modifying the original inputs, as references are considered safer than pointers.

Besides the above, and cases where references are mandatory, are there other reasons/use cases to use references as opposed to already-existing variables that the references point to?

Edit: Note that I said Besides the above. Meaning I want to know when else references are useful - when not required - outside of calling functions (I already know that). I also specifically want to know when references are preferred over the original variables, not over pointers (I already learnt from another question to "use references when you can, pointers when you must" when it comes to choosing between the two).

like image 271
thegreatjedi Avatar asked Nov 24 '15 05:11

thegreatjedi


2 Answers

Lets say you have a large structure, or a std::vector or a std::string object, and you pass that by value to a function. That means that the object is copied which might be quite inefficient for large object (like say a vector of a couple of million entries). Then you can use a reference to a constant object like e.g. std::vector<SomeType> const& my_object.

like image 135
Some programmer dude Avatar answered Nov 16 '22 15:11

Some programmer dude


We use Reference because of the following things

  1. To modify local variables of the caller function.

  2. For passing large sized arguments.

  3. To avoid Object Slicing.

  4. To achieve Run Time Polymorphism in a function.

For more info, see http://www.geeksforgeeks.org/when-do-we-pass-arguments-by-reference-or-pointer/

like image 43
Murali Manohar Avatar answered Nov 16 '22 15:11

Murali Manohar