Developer knowledge network · moderated exchange

Zajednica UnreliableCode

Zajednica za istraživanje, obrnuti inženjering i programiranje programera

Knowledge indexŽivjeti
4Categories
919Threads
2.8KPostovi
Guide

How to write exception-safe code with the Strong Exception Guarantee and Copy-and-Swap Idiom [StackOverflow Architecture Guide]

raii_clean_coder
Modern C++ Advocate
MEMBER
Rep: 190
Datum pridruživanja: Aug 2020
Postovi: 20
Hvala: 22
prije 1 mjeseci · Jun 29, 2026 11:36 PM
#1

The Copy-and-Swap idiom provides the Strong Exception Guarantee (either the operation succeeds completely, or the object remains unmodified in its original state):

CPP
class SmartBuffer {
    size_t m_size;
    int* m_data;
public:
    friend void swap(SmartBuffer& first, SmartBuffer& second) noexcept {
        std::swap(first.m_size, second.m_size);
        std::swap(first.m_data, second.m_data);
    }
    SmartBuffer& operator=(SmartBuffer other) noexcept { // Pass by value (creates copy)
        swap(*this, other); // Swap with temporary copy
        return *this;
    } // Old data is safely destroyed when temporary 'other' leaves scope!
};
modern_cpp_artisan
C++ Template Wizard
MEMBER
Rep: 124
Datum pridruživanja: Jun 2019
Postovi: 29
Hvala: 72
prije 1 mjeseci · Jun 30, 2026 2:53 AM
#2

Pass-by-value in the assignment operator combined with noexcept swap gives you copy-assignment and move-assignment in one single elegant method.

sanitizer_sam
UB Hunter
MEMBER
Rep: 119
Datum pridruživanja: Apr 2021
Postovi: 10
Hvala: 53
prije 1 mjeseci · Jun 30, 2026 7:54 AM
#3

Guarantees that if memory allocation fails during copying, the original object is left 100% intact.