N
N
Nexeon2015-12-30 14:31:32
C++ / C#
Nexeon, 2015-12-30 14:31:32

When is it acceptable to return a reference in a function? When are references to a constant?

Hello everyone, I'm a beginner in C++.
A little confused with the concept of a reference return value in a function, as well as a return value in the form of a reference to a constant. (int &func() and const int &func())
Who can clearly explain how they differ and for what purposes they are used?
It is desirable with examples, I will be very grateful.
PS In Google I could not find a complete answer to the question.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander Ruchkin, 2015-12-30
@MrNexeon

They differ in that in the second case, the object by reference cannot be changed. They differ from returning by value in that when returning by value, an object is copied with all the consequences:
1. It can be expensive
2. The result is a copy, so the changes made to it are changes in the copy, and not in that object, who was returning. For this reason, for example, the operator [] of an array class must return a reference, so that changing the received reference would change the value that lies in the array.
A reference is no different from a pointer in this sense, except that it cannot be null. Therefore, you cannot, for example, return a reference to some temporary variable:

int & foo()
{
  int x = 100;
  return x;
}
int main()
{
  int & y = foo();
  y = 10; // UB
}

The variable x here will die when foo exits, and y will refer to an already dead variable. But it is possible to return a reference to a class member if the class object will live longer than the reference. Those. so it is possible:
class Test
{
  int x;
public:
  int & getx() { return x; }
};
int main()
{
  Test t;
  int & y = t.getx();
  y = 10; // t.x будет равен 10
}

But again, no:
class Test
{
  int x;
public:
  int & getx() { return x; }
};
int main()
{
  int * y;
  {
    Test t;
    y = &t.getx();
  }
  *y = 10; // UB, t умирает в конце блока, x тоже, а обращение идёт уже после
}

V
Vitaly, 2015-12-31
@vt4a2h

PS In Google I could not find a complete answer to the question.

Badly searched, here are the first three links (everything is explained there and very, very detailed):
https://stackoverflow.com/questions/795674/which-a...
https://isocpp.org/wiki/faq/const- correctness
www.bogotobogo.com/cplusplus/object_returning.php
There are examples with operators, etc.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question