Developer knowledge network ยท moderated exchange

Onbetrouwbare Code-gemeenschap

Ontwikkelaarsonderzoek, reverse engineering en coderingsgemeenschap

Knowledge indexLive
4Categories
919Threads
2.8KBerichten
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
Vertegenwoordiger: 190
Datum van deelname: Aug 2020
Berichten: 20
Bedankt: 22
1 maanden geleden ยท 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
Vertegenwoordiger: 124
Datum van deelname: Jun 2019
Berichten: 29
Bedankt: 72
1 maanden geleden ยท 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
Vertegenwoordiger: 119
Datum van deelname: Apr 2021
Berichten: 10
Bedankt: 53
1 maanden geleden ยท Jun 30, 2026 7:54 AM
#3

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