On Aug 10, 11:12 am, Jianwei Sun <jsunnewsgr...@gmail.com> wrote:
I am reading a peice of code which is at the following
link:http://www.brpreiss.com/books/opus4/html/page141.html#SECTION007
12300...
The code is like this:
Object& StackAsLinkedList::Pop()
{
if(count==0)
throw domain_error("stack is empty");
Object& const result=*list.First();
list.Extract(&result);
--count;
return result;
}
Does this code return a reference to local variable result? If this
is the
case, then this code
has problem?
the function returns a reference (as required since the function's
return type is Object&).
The declaration for result is a const reference:
Object& const result(*list.First());
In effect, you aren't dealing with a temporary variable. Passing
references by value doesn't magicly allocate or deallocate its
referant.
Whether the code is correct is unknown to us. In particular, no-one
here knows what happens to result (the Object) during and after the
call to list.Extract(&result). We have no way of knowing how (or if)
the list is managing the Object lifetimes.
http://www.brpreiss.com/books/opus4/html/page98.html#SECTION0052100000000000000000
this won't be correct.
If the extact doesn't delete this node, this will work fine.