1 2 3 4
|
Foo foo;
Foo& bar = foo;
Foo& gaz = bar;
Foo& fubar = gaz;
|
is harder to follow than
1 2 3 4
|
Foo foo;
Foo& bar = foo;
Foo& gaz = foo;
Foo& fubar = foo;
|
In the first we do create reference from reference (gaz from bar and fubar from gaz).
The second creates all references from the original object.
Neither seems beneficial; why have so many aliases for same object?
Incidentally, we are quite likely to have function that takes argument by reference and calls another function with that argument. The other function(s) take by reference too. In that sense "reference from reference" might be surprisingly common.
1 2 3
|
struct Foo {
Foo& func();
};
|
Lets do:
1. Change struct to class (no real change)
2. Rename Foo
3. Add a parameter for func
4. Rename func
For example:
1 2 3 4
|
class Obstacle {
public:
Obstacle & Obstacle::operator= (const Obstacle & other);
};
|
Is that not a structure that has a member function that returns a reference? Quite legit.
I did not say which objects reference does the Foo::func() return. That was irrelevant. The point was that in both A and B a reference was assigned to
gaz
.
On the last example ... func() being a member function was not important. Unnecessary confusion. My bad.
Again, what is wrong in:
1 2 3 4
|
Bar& fubar() {
Bar snafu;
return snafu;
}
|
What is the
lifetime of object snafu?
It is created and destroyed within the function call.
When the call to fubar() has returned, the snafu does not exist any more.
However, the caller could store the returned reference.
What happens, if you try to access an object that does not exist any more?