149. Self-Assignment Check

In C++, the assignment operator (=) is just a function. If you write obj = obj; (assigning an object to itself), a naive implementation might destroy the object's data before trying to copy it, leading to corruption or crashes. This is especially dangerous with resources like buffers or file handles.

To prevent this, every assignment operator must first check: "Is the source address the same as my address?"

Your task is to implement a class Buffer.

  1. Private member: int id.
  2. Constructor: Buffer(int i) : id(i) {}.
  3. Operator= (Assignment):
    • Check if (this == &other).
    • If true, print Self-Assignment Detected and return *this immediately without changing anything.
    • If false, copy id from other, print Assignment Complete, and return *this.
  4. Method void log(): Print Buffer ID: <id>.

Program Flow:

  1. Read integer N.
  2. Loop N times.
  3. Read string cmd.
  4. If cmd is "ASSIGN":
    • Read two integers id1 and id2.
    • Create two Buffer objects (b1, b2) with these IDs.
    • Perform b1 = b2;.
    • Call b1.log().
  5. If cmd is "SELF":
    • Read integer id.
    • Create Buffer b1(id).
    • Perform b1 = b1; (Self-Assignment).
    • Call b1.log().

Input Format:

  • First line: Integer N.
  • Next N lines: String cmd, followed by values.
  • Input is provided via standard input (stdin).

Output Format:

  • "ASSIGN": Assignment Complete followed by Buffer ID: <new_id>
  • "SELF": Self-Assignment Detected followed by Buffer ID: <original_id>
  • Each output on a new line.

Example: 

Example 1

Input:

2
ASSIGN 10 20
SELF 99

Output:

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

Constraints:

  • Must use if (this == &other) inside operator=.
  • Must return *this to allow chaining.

 

 

 

 

Loading...

Input

2 ASSIGN 10 20 SELF 99

Expected Output

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