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
Self-assignment
Self-assignment is assigning an object to itself through an assignment operator.
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
- undefined behaviorproduces · Undefined behavior is program execution for which the applicable language or system specification imposes no requirements on the resulting behavior or effects.
- copy assignment operatorcontrasts with · A copy assignment operator is a C++ special member function that copies state from one object into an already existing object of a compatible type.
- referenceused by · A reference is an indirect value or relationship that identifies or provides access to another value, object, resource, or source.
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.
