Improve security and implement copy and swap elegantly: Copy-and-Swap usage in C++

Overview: Copy-and-Swap is a common practice in C++ programming to implement assignment operators and exception-safe copy constructors. The core idea is to create a temporary copy through the copy constructor, and then ensure the exception safety of the operation through exchange. This approach works both before and after C++11, but in C++11, the introduction of move semantics and rvalue references makes the implementation more efficient.

Copy-and-Swap is a idiom in C++ programming, usually used to implement assignment operators and exception-safe copy constructors. The basic idea is to use a copy constructor to create a temporary copy, and then ensure exception safety by exchanging the temporary copy with the contents of the current object.

#include <iostream>
#include <algorithm> // For std::swap

class MyClass {
public:
    // 构造函数和其他成员函数的实现...

    // 拷贝构造函数
    MyClass(const MyClass& other) : data(new int(*other.data)) {}

    // 拷贝并交换
    friend void swap(MyClass& first, MyClass& second) noexcept {
        using std::swap;
        swap(first.data, second.data);
    }

    // 赋值操作符
    MyClass& operator=(MyClass other) {
        swap(*this, other); // 利用拷贝构造函数创建临时副本
        return *this;
    }

    // 析构函数
    ~MyClass() {
        delete data;
    }

private:
    int* data;
};

int main() {
    MyClass obj1;
    MyClass obj2 = obj1; // 调用拷贝构造函数
    MyClass obj3;
    obj3 = obj1; // 调用赋值操作符

    return 0;
}

In this example, the swap function implements the exchange of data members of two objects, while the assignment operator uses the copy constructor to create a temporary copy of the incoming object, and then ensures exception safety through the exchange. This approach is basically the same before and after C++11, but move semantics and rvalue references are introduced in C++11, which can be further optimized.