149. Self-Assignment Check

#include <iostream>
#include <string>

class Buffer {
private:
    int id;

public:
    Buffer(int i) : id(i) {}

    // Standard signature for copy assignment operator
    Buffer& operator=(const Buffer& other) {
        // Step 1: Self-assignment check
        // 'this' is a pointer to the current object.
        // '&other' is the address of the source object.
        if (this == &other) {
            std::cout << "Self-Assignment Detected" << std::endl;
            // Return current object immediately, do NOT modify anything
            return *this; 
        }

        // Step 2: Normal assignment logic
        id = other.id;
        std::cout << "Assignment Complete" << std::endl;

        // Step 3: Return reference to support chaining (a = b = c)
        return *this;
    }

    void log() {
        std::cout << "Buffer ID: " << id << std::endl;
    }
};

int main() {
    int N;
    if (!(std::cin >> N)) return 0;

    for (int i = 0; i < N; ++i) {
        std::string cmd;
        std::cin >> cmd;

        if (cmd == "ASSIGN") {
            int i1, i2;
            std::cin >> i1 >> i2;
            Buffer b1(i1);
            Buffer b2(i2);
            b1 = b2;
            b1.log();
        } else if (cmd == "SELF") {
            int i1;
            std::cin >> i1;
            Buffer b1(i1);
            b1 = b1; // This triggers the self-assignment check
            b1.log();
        }
    }
    return 0;
}

Explanation & Logic Summary:

  • The Pointer Comparison: this holds the memory address of the object on the left side of the = sign. &other holds the address of the object on the right side. If these addresses are equal, they are the same physical object in memory.
  • Why Return *this? C++ allows chaining assignments: a = b = c. The expression b = c must evaluate to a reference to b so that a can copy from it.

Firmware Relevance & Real-World Context:

  • Safe Resource Management: Imagine a class that manages a hardware DMA channel. If you assign dma1 = dma1, a naive implementation might "Stop and Release" the channel before "Acquiring" it. Since it's the same object, you've just released the channel you were trying to use, causing a hard crash. The if (this == &other) check prevents this catastrophe.

 

 

 

 

Loading...

Input

2 ASSIGN 10 20 SELF 99

Expected Output

Assignment Complete Buffer ID: 20 Self-Assignment Detected Buffer ID: 99