Developer knowledge network ยท moderated exchange

UnreliableCode Community

Developer Research, Reverse Engineering & Coding Community

Knowledge indexLive
4Categories
919Threads
2.8KPosts
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
Join Date: Aug 2020
Posts: 20
Thanks: 22
1 months ago ยท 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
Join Date: Jun 2019
Posts: 29
Thanks: 72
1 months ago ยท 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
Join Date: Apr 2021
Posts: 10
Thanks: 53
1 months ago ยท Jun 30, 2026 7:54 AM
#3

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