Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

Exception safety: guarantees and copy-and-swap

Exception-safety guarantees specify what remains after an operation fails: valid state, unchanged state, or no escaping exception. Copy-and-swap can provide the strong guarantee by preparing a copy before committing a change.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

T& operator=(const T& other) { T temporary(other); swap(temporary); return *this; }
void swap(T& other) noexcept;

Exception safety describes an operation's contract, not merely its use of try and catch. The basic guarantee preserves object invariants and prevents resource leaks, but allows values to change after an exception. The strong guarantee additionally promises that a failed operation has no effects within the scope of its contract: it either completes entirely or leaves that state unchanged.

The no-throw guarantee means that an operation does not propagate exceptions. Writing noexcept alone does not prove correct error handling: an exception attempting to escape such a function invokes std::terminate rather than rolling changes back. Guarantees are documented per operation; the presence of a catch does not establish them.

Copy-and-swap implements strong exception safety for assignment: first construct temporary, then commit through a non-throwing swap. If copying fails, the target has not yet changed. After the swap, the temporary holds the old state and releases it on destruction. This technique requires copying without modifying the original, a non-throwing swap, and safe destruction. Its cost can include an extra copy and allocation; external effects such as file writes are not automatically undone.

RAII ties resources to object lifetimes: stack unwinding destroys already-constructed local objects. Destructors should clean up without propagating exceptions. If an exception escapes a destructor invoked by stack unwinding, std::terminate is called. But if cleanup code calls a potentially throwing destructor in the ordinary course of execution, a catch within that cleanup code can catch an exception from that destructor, even while the stack is still unwinding because of the original exception. The standard requires non-throwing destructors in the standard library. The supplied sources are a rolling standard draft, not a frozen C++23 text.

Reference identifiers covered by this entry: Basic, strong and no-throw guarantees; copy-and-swap.

Examples

#include <iostream>

struct CopyFailure {};

class Value {
    int number_;
public:
    inline static bool fail_copy = false;

    explicit Value(int number) noexcept : number_(number) {}

    Value(const Value& other) : number_(other.number_) {
        if (fail_copy) throw CopyFailure{};
    }

    void swap(Value& other) noexcept {
        int old = number_;
        number_ = other.number_;
        other.number_ = old;
    }

    Value& operator=(const Value& other) {
        Value temporary(other);
        swap(temporary);
        return *this;
    }

    int get() const noexcept { return number_; }
};

int main() {
    Value target(7), source(42);
    Value::fail_copy = true;
    try {
        target = source;
    } catch (const CopyFailure&) {
        std::cout << "after failure: " << target.get() << '\n';
    }
    Value::fail_copy = false;
    target = source;
    std::cout << "after success: " << target.get() << '\n';
}

Result

after failure: 7
after success: 42

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources