liveBook · Manning

Self-assignment

As explained in 100 C++ Mistakes and How to Avoid Them

Self-assignment is assigning an object to itself through an assignment operator.

Self-assignment occurs when an object is assigned to itself, such as `mustang = mustang`. It becomes dangerous when a copy assignment operator deletes a resource before reading the source. Because the source and target are the same object, the later read accesses deleted data, causing data loss, crashes, or undefined behavior. section 9.5

How 100 C++ Mistakes and How to Avoid Them covers it

How deep it goes
Works through deletion, dangling access, and an identity guard, while deferring broader resource-management design.
Examples
Uses `mustang = mustang`, array assignments, pointer dereferences, and `InputReader` resource-copying scenarios.
What it assumes
Assumes familiarity with copy assignment, pointers, dynamic resources, and class invariants.
What you can do after
Diagnose/debug self-assignment failures with Valgrind and memory sanitizers, then add an identity guard before resource replacement.
How it connects
Connects copy assignment operators with copy constructors, dynamic resources, class invariants, and move assignment operators.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 C++ Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.