Developer knowledge network ยท moderated exchange

Komunitas Kode Tidak Dapat Diandalkan

Riset Pengembang, Rekayasa Terbalik & Komunitas Pengkodean

Knowledge indexHidup
4Categories
919Threads
2.8KPostingan
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
Reputasi: 190
Tanggal Bergabung: Aug 2020
Postingan: 20
Terima kasih: 22
1 bulan yang lalu ยท 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
Reputasi: 124
Tanggal Bergabung: Jun 2019
Postingan: 29
Terima kasih: 72
1 bulan yang lalu ยท 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
Reputasi: 119
Tanggal Bergabung: Apr 2021
Postingan: 10
Terima kasih: 53
1 bulan yang lalu ยท Jun 30, 2026 7:54 AM
#3

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