8

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?

ahala
  • 4,683
  • 5
  • 27
  • 36
  • isn't a pointer a reference? – Sam I am says Reinstate Monica Aug 05 '13 at 17:48
  • @SamIam: If they were the same thing and had the same meaning, why would you think they would even have been introduced in the language in the first place ? – ereOn Aug 05 '13 at 17:52
  • 1
    Think about how would you implement subscript operator of say, `vector`, without returning a reference. – jrok Aug 05 '13 at 17:52
  • `operator <<`, `operator >>` , `operator=`, etc – Cubbi Aug 05 '13 at 17:55
  • @jrok You can implement subscript operator without returning a reference (as in a &). If it's const method, you could return the item by value. (Not saying it's good/bad, just you could). You could also return a proxy object by value that somehow refers to the item internally. – Neil Kirk Aug 05 '13 at 17:56
  • @ereOn to make nicer syntax for eg operator overloading. A reference is essentially a pointer with some restrictions, couple of special rules and a different syntax but, so long as you forgo some syntax niceties, there is nothing you can do with a reference you couldn't do with a pointer. – Neil Kirk Aug 05 '13 at 17:58
  • @NeilKirk: It's all about semantics. That's why we have stuff like `std::optional`: because *meaning matters*. I know of course, what a reference really is. My point is just that if your function returns a pointer instead of a reference because you think those two are the same, you are doing it wrong. – ereOn Aug 05 '13 at 18:01
  • @ereOn That's true but I was answering the question you posed. References were added to the language for operator overloading. – Neil Kirk Aug 05 '13 at 18:05
  • 1
    I do not think this is a duplicate question. it is asking whether there is situation that one must return a reference, not about when one could return reference. – ahala Feb 22 '16 at 20:18
  • How is this a duplicate question? cmon.. – csguy Sep 10 '19 at 00:58

5 Answers5

9

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

ani627
  • 5,578
  • 8
  • 39
  • 45
jrs
  • 606
  • 3
  • 5
  • 3
    +1 for the reference to C++FAQ – SteveLove Aug 05 '13 at 17:56
  • Thanks. This is a convincing example. – ahala Aug 05 '13 at 18:05
  • @ahala can you mark as answered if you feel I answered your question thoroughly? – jrs Aug 05 '13 at 21:17
  • There are two reasons to make such a declaration: 1. The information being returned is a large enough object that returning a reference is more efficient than returning a copy. 2. The type of the function must be an l-value. https://learn.microsoft.com/en-us/cpp/cpp/reference-type-function-returns?view=vs-2019 – csguy Sep 10 '19 at 02:13
4

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

SteveLove
  • 3,137
  • 15
  • 17
1

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?

Community
  • 1
  • 1
Gabriel
  • 3,564
  • 1
  • 27
  • 49
  • 1
    The post linked discusses the question on the other side, not on when we must return references or when returning reference is better than returning pointers. – ahala Aug 05 '13 at 18:10
0

Returning a reference from a function has the same advantages and disadvantages as returning a pointer.

Returning a non-const reference or pointer allows the caller to write to member variables and call non-const member functions.

However, the object referred to had better have a lifetime longer than the caller requires otherwise the program goes into the realms of undefined behaviour.

On the subject of must return a reference, it is useful for syntactic sugar as with operators, which if returning pointers would require the caller to dereference the pointer.

quamrana
  • 37,849
  • 12
  • 53
  • 71
  • 2
    except when someone returns a nullptr ;) – BЈовић Aug 05 '13 at 17:50
  • 3
    I would not downvote for that, but this first statement seems quite wrong to me. Pointers and reference are close indeed, but they are definitely different beasts and don't have the exact same advantages/disadvantages in a function return context. – ereOn Aug 05 '13 at 17:54
0

Just remember that you need to return a reference to an object which will exist after the function is terminated. For example, you can do something like this:

Val(X,10) = 1;

where Val is a function which returns (say) a reference to the 10th element in a list thus setting it to 1.

Jacob
  • 34,255
  • 14
  • 110
  • 165