I am programming in C++ more then 5 years, and have never met any place where reference of the variable is recommended to use except as a function argument (if you don’t want to copy what you pass as your function argument). So could someone point cases where C++ variable reference is recommended (I mean it gives any advantage) to use.
Share
As a return value of an opaque collection accessor/mutator
The
operator[]ofstd::mapreturns a reference.To shorten the text needed to reference a variable
If you miss old-school
with Foo do ...statement (that’s Pascal syntax), you can writeanother example of this can be found in Mike Dunlavey’s answer
To state that something is just a reference
References are also useful in wrapper objects and functors–i.e. in intermediate objects that logically contact no members but only references to them.
Example:
The idea here that it’s a compile error if you don’t initialize a reference in constructor of such an object. The more checks in compile time–the better programs are.