skip to content
Ivan's wiki
Site Tools
Search
Tools
Show pagesource
Backlinks
Recent Changes
Media Manager
Sitemap
>
Recent Changes
Media Manager
Sitemap
cpp-self-assignment
This page is read only. You can view the source, but not change it.
# C++ self-assignment **[Self-assignment](https://en.cppreference.com/w/cpp/language/copy_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. ```cpp // 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; } ```
Page Tools
Show pagesource
Backlinks
Back to top