What is the Copy-and-Swap idiom in C++ and when should I use it?
Hi everyone! I started learning C++ and I'm trying to figure out the correct way to override the assignment operator. I know I need to handle self-assignment and free old resources, but my code looks terrible and I keep making mistakes.\n\nHere's an example of my class for working with a dynamic array:\n```cpp\nclass MyArray {\n int* data;\n size_t size;\npublic:\n MyArray(size_t s) : size(s), data(new int[s]) {}\n ~MyArray() { delete[] data; }\n \n // Problematic assignment operator\n MyArray& operator=(const MyArray& other) {\n if (this != &other) { // self-assignment check\n delete[] data; // free old data\n size = other.size;\n data = new int[size]; // allocate new memory\n std::copy(
No answers yet.
Log in to leave an answer