Developer knowledge network · moderated exchange

Сообщество UnreliableCode

Сообщество разработчиков, обратного проектирования и кодирования

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
Представитель: 190
Дата присоединения: Aug 2020
Сообщения: 20
Спасибо: 22
1 месяцев назад · 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
Представитель: 124
Дата присоединения: Jun 2019
Сообщения: 29
Спасибо: 72
1 месяцев назад · 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
Представитель: 119
Дата присоединения: Apr 2021
Сообщения: 10
Спасибо: 53
1 месяцев назад · Jun 30, 2026 7:54 AM
#3

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