What should the 'pop()' method return when the stack is empty?
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 a std::logic_error
, but that would not be required. In C, my implementation would abort
via assert
.
The caller of pop
is responsible for ensuring that the precondition that the stack is not empty holds before calling pop
. The stack should therefore have an isEmpty
method for the caller to check.
The C++ STL actuall doesn't return anything via pop()
since it decouples returning the value of an object and actually popping an object off the stack's internal data-structure, making them two separate functions. So that's another option to consider in your design of a stack data-structure.
Your third option is also a pretty idiomatic approach for these types of data-structures.
For your fourth option, rather than a "unique empty element", I would actually do a variation on your third option where your pop()
function that takes a pointer argument rather than a reference type, and returns NULL if there are no objects left in the stack.