Reputation: 17193
I don't understand when I would ever want to return a reference from a function (i.e. T& func(){...}
).
For example:
T& func() {
Something t;
return t;
}
This creates a Something
instance named t
, and then returns it by reference. When we go out of scope, t
is lost. So the reference is referring to 0
I think..?
So in other words, why would I ever want to return either a reference or a const reference? Please explain and give examples.
Upvotes: 2
Views: 101
Reputation: 35440
Returning a reference to the current object is used for implementing a user-defined assignment operator.
class Foo
{
Foo& operator=(const Foo&);
//...
};
It is also used as a return type when implementing overloads of operators +=
, -=
, *=
, etc. These operators suggest that the return type is the adjusted current object, not a new object. Therefore to return the current object, you return a reference to *this
.
Upvotes: 0
Reputation: 36896
You can think of references as little more than pointers. Any time you'd return a pointer from a function, you might return a reference type instead.
I think your issue with returning references is the issue of scope. As long as there are no scope issues, it's just another tool at your disposal.
Upvotes: 0
Reputation: 48615
Sometimes you return a reference to a static variable defined in a function:
T& func() {
static Something t; // this will exist until program closes
return t;
}
That's a technique to help combat problems involving the order of static initialization.
Obviously member variables can make sense (I'm sure you're not asking about those though):
T& MyType::func() {
return this->t; // persists with the object
}
Also sometimes you want to return the object that was passed in to the function:
std::ostream& operaor<<(std::ostream& os, const MyType& t) {
// blah blah
return os; // pass it back out
}
That enables you to chain functions together like:
if(std::getline(input >> size >> std::ws, line))
{
// size and line were successfully read here
}
Upvotes: 1
Reputation: 16056
You often do it when you are returning a member from one of the function's arguments. An example from the standard library:
template<class T, size_t n>
struct array
{
T data[n];
T& operator[](size_t i) { return data[i]; }
};
Upvotes: 3