Introduction to Stacks using std::stack

Exception safety with std::stack

What happens if an exception is thrown while I'm modifying a std::stack? Is it exception-safe?

Illustration representing computer hardware

Yes, std::stack is designed to be exception-safe. The C++ Standard Library guarantees that all operations on std::stack either succeed completely or have no effect if an exception is thrown. This is known as the strong exceptionΒ guarantee.

Let's look at what this means for some commonΒ operations:

  1. push()Β orΒ emplace(): If an exception is thrown during the insertion of a new element (either due to a copy/move operation or due to the container running out of memory), the stack remains unchanged. The element is not added, and any elements previously in the stack are still present and unchanged.
  2. pop(): If an exception is thrown during the removal of the top element, the element is still removed. No elements are left in an invalid or unspecified state.

Here's anΒ example:

#include <iostream>
#include <stack>

class MyClass {
 public:
  MyClass(int id) : id(id) {
    if (id == 4) {
      throw std::runtime_error(
        "Cannot copy MyClass with id 2");
    }
  }

  int id;
};

int main() {
  std::stack<MyClass> s;

  try {
    s.emplace(1);
    s.emplace(2);
    s.emplace(3);
    s.emplace(4);  // this will throw
  } catch (...) {
    std::cout << "Exception caught! stack size: "
      << s.size() << '\n';
  }

  // The stack is still in a valid state
  while (!s.empty()) {
    std::cout << s.top().id << ' ';
    s.pop();
  }
}
Exception caught! stack size: 3
3 2 1

In this code, when the stack tries to copy an instance of MyClass with id 2, an exception is thrown. However, the stack remains in a valid state. The element with id 1, which was previously inserted successfully, is still present and can be accessedΒ normally.

The strong exception guarantee is an important property that allows you to write robust, error-resistant code. It means that if an exception is thrown, you don't need to worry about your stack being left in an inconsistent or corruptedΒ state.

Answers to questions are automatically generated and may not have been reviewed.

Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright Β© 2024 - All Rights Reserved