Answer the question
In order to leave comments, you need to log in
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
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
}
class Test
{
int x;
public:
int & getx() { return x; }
};
int main()
{
Test t;
int & y = t.getx();
y = 10; // t.x будет равен 10
}
class Test
{
int x;
public:
int & getx() { return x; }
};
int main()
{
int * y;
{
Test t;
y = &t.getx();
}
*y = 10; // UB, t умирает в конце блока, x тоже, а обращение идёт уже после
}
PS In Google I could not find a complete answer to the question.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question