Site Tools


wiki:cpp-self-assignment

Table of Contents

C++ Self-assignment

Self-assignment is when an object is assigned to itself: a = a. Without defensive checks, a naive copy assignment operator that deletes the old data before copying the new data will delete the source data and then try to copy from it, causing undefined behavior.

Check for self-assignment at the start of copy assignment: if (this == &other) return *this;, or use copy-and-swap which handles it automatically.

Example

This example shows the self-assignment problem and two safe solutions.

// compile: g++ -o self self.cpp
// run: ./self
// description: self-assignment handling in copy assignment
 
#include <iostream>
 
class Buffer {
private:
    int* data;
    size_t size;
public:
    Buffer(size_t n = 0) : size(n), data(new int[n]) {}
    ~Buffer() { delete[] data; }
 
    Buffer& operator=(const Buffer& other) {
        if (this == &other) return *this;  // check for self-assignment
 
        delete[] data;
        size = other.size;
        data = new int[size];
        std::copy(other.data, other.data + size, data);
 
        return *this;
    }
 
    // Or use copy-and-swap (handles self-assignment automatically)
};
 
int main() {
    Buffer b(10);
    b = b;  // self-assignment: safe with check
 
    return 0;
}
wiki/cpp-self-assignment.md · Last modified: by 127.0.0.1