Sobes.tech
Middle

What security guarantees do you know?

sobes.tech AI

Answer from AI

Safety guarantees in C++11 and later versions are divided into three types:

  1. Basic Guarantee: If a function completes, the program remains in a correct, but possibly undefined state. No resource leaks occur, but data may be partially modified. If the function terminates with an exception, resources acquired within the function before the exception are released.

  2. Strong Guarantee: If a function completes, its state is either fully consistent with successful completion or remains unchanged as before the call if it terminates with an exception. This implies rollback resilience.

  3. No Except Guarantee: The function guarantees not to throw exceptions. It may complete successfully or terminate abnormally (e.g., via std::terminate), but not through the C++ exception mechanism.

Examples:

  • The copy-and-swap idiom is often used for the strong guarantee:

    class MyClass {
    public:
        // ...
        void swap(MyClass& other) noexcept { // No exception guarantee
            using std::swap;
            swap(data_, other.data_); // Assuming swap(T&) does not throw
        }
    
        // Strong guarantee
        MyClass& operator=(MyClass other) { // Pass by value for copying
            swap(other);
            return *this;
        }
    private:
        DataType* data_; // Example resource
    };
    
  • std::vector::push_back: Usually provides the basic guarantee when adding an existing object. It can provide the strong guarantee if copying/moving the element does not throw exceptions. Reallocation may throw exceptions.

  • Functions marked noexcept must adhere to the no exception guarantee.

Application:

  • When designing APIs, it is important to clearly specify what guarantee each function provides.
  • When handling exceptions, consider what guarantee is provided by the functions called within a try block to manage state correctly.
  • The strong guarantee often requires additional costs (e.g., temporary copying), so it is used where this is critical.
  • The no exception guarantee is important for low-level code and functions called from noexcept contexts (e.g., destructors).