🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

1 total messages Started by Wil Evers Wed, 06 Mar 1996 15:44
Re: STL pop_back()
#3598
Author: Wil Evers
Date: Wed, 06 Mar 1996 15:44
63 lines
2855 bytes
In article <4hhsta$2gk@news.BelWue.DE>
kuehl@uzwil.informatik.uni-konstanz.de (Dietmar Kuehl) writes:

> However, 'stack<...>::pop()' also returns 'void'. The
> reason is simple: If you need the value, you can get it with a sequence
> of 'top()' and 'pop()' operations. Requiring that 'pop()' returns an
> object would make it necessary to create this object which in turn can
> be expensive. This way it is defined everything is possible
> efficiently.

Actually, I can think of another reason. Assuming the stack is defined as a
robust throw-and-keep class - meaning its member functions leave the stack
in its old state when they report an exception - then having a pop() that
both returns the top element and discards it may still lead to trouble for
its users. If we write:

	try {
		someObj = someStack.pop();
	}
	catch (..) {
		// state of someStack??? (*)
	}

then, when we get to (*), we don't know what happened. Did the exception
come from someStack.pop(), so the stack is still in its old state, or did
it come from the assignment to someObj, so the stack is in its new state
and the top element is lost? Recovering will be nearly impossible, so the
stack should probably be shut down.

If we have a separate member function to get the top element (`T stack<T>
top() const') and one to discard it (`void stack<T>::pop() throw()'), users
can write:

	try {
		someObj = someStack.top();
	}
	catch (..) {
		// no harm done: report the error
		return;
	}

	// top element now safely stored in someObj:
	// remove it from the stack
	someStack.pop();

From this, I conclude that non-const member functions in a robust
throw-and-keep class should only be allowed to return objects of a type T
if both's T's copy constructor and assignment operator are known not to
throw any exceptions. For more on throw-and-keep resources, see Harald
Mueller's article in the January 1996 issue of the C++ Report.

- Wil

Wil Evers, <wil@ittpub.nl>
ITT Publitec Research and Development BV, Amsterdam, Holland


[ comp.std.c++ is moderated.  To submit articles: Try just posting with your
                newsreader.  If that fails, use mailto:std-c++@ncar.ucar.edu
  comp.std.c++ FAQ: http://reality.sgi.com/austern/std-c++/faq.html
  Moderation policy: http://reality.sgi.com/austern/std-c++/policy.html
  Comments? mailto:std-c++-request@ncar.ucar.edu
]
Thread Navigation

This is a paginated view of messages in the thread with full content displayed inline.

Messages are displayed in chronological order, with the original post highlighted in green.

Use pagination controls to navigate through all messages in large threads.

Back to All Threads