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).
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
.
We use Reference because of the following things
To modify local variables of the caller function.
For passing large sized arguments.
To avoid Object Slicing.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With