Stuff created 'on-the-fly', like variables in functions, are allocated in a special part of memory called 'the stack'. You can imagine it as something like an array of bytes where there is stuff used and stuff not used:
1 2
|
unsigned char the_stack[5000];
unsigned char* stack_pointer = &the_stack[0];
|
Every time a function is called, parts of the stack get used and
stack_pointer gets moved to point to the free space on the stack.
Things that the stack are used for are:
-- the address of where in the code to
return to
-- values for arguments to the function
-- space for variables declared inside the function
-- etc
Keep in mind, this is a very simplistic explanation of what happens, but it is also essentially correct.
So when you call the function
List<T>::rbegin() and create that unnamed
ListIterator<T>(backPtr) object, it is placed on the stack. (It may not have a name, but it must exist somewhere.)
Now, you take a reference to that object -- which is essentially a pointer to some place
currently used on the stack -- and then you
return. The object goes out of scope, is destructed, and the stack_pointer is adjusted back to what it was before
List<T>::rbegin() was called.
Now you have a pointer or reference to a place on the stack that is considered unused. At any point, some other function, or even a piece of code, may use that piece of the stack for something entirely unrelated.
See the problems? Were you allowed to return a reference to a local object (variable in a function):
-- The referenced object would have
already been destructed and left in an unusable state
-- The referenced object could actually be part of one or more
other objects.
Returning by value gets you a
copy of the function's local object, so that the
copy is guaranteed to be perfectly valid.
Hope this helps.