Possible Duplicate:
C++ STL stack question: Why does pop() not throw an exception if the stack is empty?
When designing a stack in C++, what should the pop() method (or front() method) return when the stack is empty? Which of the following design is better?
- Throw an exception
- Undefined, but require the user calling isempty() method to check before calling pop()
- Return a bool code, while using an extra parameter (a reference) to pass the popped element
- Define an unique empty element
OK, I see that my question is not that clear, let me try to rewrite it:
There are some data structures which can be implemented based on linked list like stack, queue, and each of them has a methods returning the front element (or the tail).
I want to know, is there any principle guideline about designing such a method regarding the case when the data is empty.
And my definition of better is “easy to use correctly and hard to use incorrectly”.
The programming-by-contract style would be that having a non-empty stack is a precondition of calling
pop, and that calling a method without meeting its preconditions has an undefined outcome. My implementation would throw astd::logic_error, but that would not be required. In C, my implementation wouldabortviaassert.The caller of
popis responsible for ensuring that the precondition that the stack is not empty holds before callingpop. The stack should therefore have anisEmptymethod for the caller to check.