MiddleDebuggingCommonNot answered yet
Why does w = w; break this operator=?
This copy-assignment works for distinct objects but corrupts w = w;.
Widget& Widget::operator=(const Widget& other) {
delete data_;
data_ = new Data(*other.data_); // other.data_ already deleted on self-assign
return *this;
}
Find and fix the bug.
On self-assignment (w = w;) it deletes data_, then dereferences the now-freed other.data_ (the same pointer) — use-after-free, UB. Fix: guard with if (this != &other), or use the copy-and-swap idiom, which is self-assignment-safe and exception-safe.
- ✗Assuming self-assignment never happens in real code
- ✗Thinking the problem is a missing return statement
- ✗Believing it leaks rather than uses freed memory
- →Why is the copy-and-swap idiom both self-assignment-safe and exception-safe?
- →How does copy-and-swap reuse the copy constructor and the destructor?