In c++, under what scenarios do we have to return a reference from a function? I understand using references as function inputs, but for function outputs, why cannot we only return values or pointers?
References are used to provide assignment to return values of functions. Sounds odd, but as an example, the array assignment operator in c++ is a function that actually returns a reference to the element at the index parameter so that it can be assigned to, e.g.
class Array {
public:
int& operator[] (const int& index);
...
};
Allowing the following syntax:
Array a;
a[4] = 192;
Inspired by the eternally helpful C++ FAQ:
https://isocpp.org/wiki/faq/references#returning-refs
I'm not sure there are any places where you must return a reference.
Overloading operator++()
springs to mind, but it's still not mandated to return a reference. The usual rules apply, though: if you can return a pointer to something, you can safely return a reference in most cases. The key thing is not to return a reference to something that goes out of scope - like a variable that is local to that function. Returning a reference to *this
is quite common.
Returning a value is a valuable thing to be able to do, because it either (A) makes a copy of the returned thing, or (B) makes maximum use of move semantics (C++11) and/or the Return Value Optimization (RVO on wikipedia).
If you don't need or want a copy, then returning by reference for value types is usually what you want, since you're unlikely to want pointer-like usage, i.e. having to dereference the returned thing with *
or ->
.
You can return a reference if the object already exists before the function is called. then it is not a problem.
This post summmarizes it well. Is the practice of returning a C++ reference variable, evil?
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