← Copy Semantics: The Copy Constructor & Copy Assignment Operator

Self-Assignment Safety

hard

main does something that looks pointless – a = a; – and a correct operator= needs to leave a completely unchanged by it. Without a self-assignment guard, this specific line is actively dangerous: other is a, so delete[] data; frees the exact array that other.data (the same pointer) is about to be read from in the copy loop right after – reading already-freed memory, which is undefined behavior and, in practice, garbage values instead of the original 0, 1, 2, ... sequence.

Add the this == &other check as the very first line of operator=: if the object being assigned from is the same object being assigned to, there’s nothing to do – return immediately, before the destructive delete[] ever runs.

Your solution

"Run" uses the sample stdin ("5"). "Submit" checks your code against all 3 test cases.

Test results

Submit your solution to run it against all test cases.

Hints

    Reference solution