Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

when does a function have to return a reference in c++ [duplicate]

Tags:

c++

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?

like image 420
ahala Avatar asked Aug 05 '13 17:08

ahala


3 Answers

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

like image 141
jrs Avatar answered Oct 03 '22 21:10

jrs


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 ->.

like image 42
SteveLove Avatar answered Oct 03 '22 22:10

SteveLove


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?

like image 39
Gabriel Avatar answered Oct 03 '22 22:10

Gabriel