In C++, what must happen when an object is move-assigned to itself, as in level[i] = std::move(level[j]) with i == j?
answer
- aliasing through two indexes
- valid, but the value may go
- the library's own promise
- guard or detach before freeing
basics
~20 sThe object must end in a valid state, though its value may be lost. The standard library promises exactly that for its own types, and a hand-written move assignment needs a this != &other guard or must detach the source before freeing.
solid answer
~50 sSelf-move rarely looks like `x = std::move(x)`; it happens through aliases, as when a compaction pass moves `level[j]` into `level[i]` and `i == j`. For its own types the standard says an object may be move-assigned to itself and, unless specified otherwise, ends in a valid but unspecified state; the *Cpp17MoveAssignable* requirement promises the old value only when the two objects differ. A hand-written move assignment must meet the same bar. A body that frees first and then copies the source's pointer loses the array but stays consistent; one that frees first and then uses `std::exchange` leaves a freed pointer behind, a double free. Either guard with `if (this != &other)` or detach the source before freeing the old array. libc++'s `std::swap(x, x)` self-move-assigns a moved-from object, so this case is reachable from ordinary code.
code
cpp · 32 lines#include <cstddef>
#include <cstdio>
#include <utility>
#include <vector>
class Buffer {
public:
explicit Buffer(std::size_t n) : size_(n), data_(new float[n]{}) {}
Buffer(Buffer&& o) noexcept
: size_(std::exchange(o.size_, 0)), data_(std::exchange(o.data_, nullptr)) {}
Buffer& operator=(Buffer&& o) noexcept {
std::size_t n = std::exchange(o.size_, 0); // detach the source first...
float* incoming = std::exchange(o.data_, nullptr);
delete[] data_; // ...then free the old array
size_ = n;
data_ = incoming;
return *this;
}
~Buffer() { delete[] data_; }
std::size_t size() const { return size_; }
private:
std::size_t size_;
float* data_;
};
int main() {
std::vector<Buffer> level;
level.emplace_back(4096);
std::size_t i = 0, j = 0; // a compaction pass where i == j
level[i] = std::move(level[j]); // self-move-assignment through an alias
std::printf("size after self-move: %zu\n", level[0].size());
}go deeper
Know that x = std::move(x) can happen through aliases and that a move assignment must not leave the object broken when it does.
Explain the library's rule: a self-moved standard object is valid but unspecified, and show the this != &other guard.
Trace a delete-then-exchange body under aliasing to the double free, fix it by detaching first, and add a sanitizer-backed self-move test.
Decide whether a codebase requires value-preserving self-move or only validity, and enforce it with a shared test for every hand-written resource type.
## How self-move reaches real code Writing `b = std::move(b);` by hand is rare, and both Clang and GCC flag it with `-Wself-move`, which each compiler's `-Wall` enables. The cases that matter go through **aliases** the compiler cannot see: - a compaction or partition pass that moves `level[j]` into `level[i]` and sometimes has `i == j`; - two references that end up naming the same element; - generic code such as libc++'s `std::swap`, whose body is `T t(std::move(x)); x = std::move(y); y = std::move(t);`, so `swap(x, x)` performs `x = std::move(x)` on an already moved-from `x`. ## What the standard promises for its own types Two library rules cover this: 1. The moved-from-state rule: an object of a standard library type **may be move-assigned to itself**, and unless otherwise specified the assignment leaves it in a **valid but unspecified state**. 2. The rvalue-argument rule: the library may assume an rvalue reference parameter is the only reference to its argument, except that the argument of a move assignment operator **may be a reference to `*this`**. The *Cpp17MoveAssignable* requirement says `t = rv` makes `t` equivalent to `rv`'s old value only **if `t` and `rv` do not refer to the same object**, and `rv` must still meet the requirements of the library component using it either way. So a self-move may lose the value; it may not leave a broken object. ## Three hand-written bodies, traced for `&other == this` | Body | Self-move result | |---|---| | `delete[] data_; data_ = other.data_; size_ = other.size_; other.data_ = nullptr; other.size_ = 0;` | array freed, object ends **empty**: valid, value lost | | `delete[] data_; data_ = std::exchange(other.data_, nullptr);` | `exchange` nulls `data_`, then returns the freed pointer into it: **double free** in the destructor | | detach first: `auto n = std::exchange(other.size_, 0); auto p = std::exchange(other.data_, nullptr); delete[] data_; size_ = n; data_ = p;` | `delete[] nullptr`, then the array is restored: **value kept** | The second row is the dangerous one: it looks tidier than the first and is wrong only when the two objects alias. AddressSanitizer reports "attempting double-free" at the destructor. The first row also reads the just-freed pointer value; copying an invalid pointer value is implementation-defined rather than undefined, but it is one more reason not to write it that way. ## The two correct fixes - **Guard:** `if (this != &other) { delete[] data_; ...take... }`. Clear, one comparison, and the self-move leaves the value intact. - **Order:** detach the source into locals, free the old array, then store the locals. No branch, and self-move is a no-op by construction. Move-and-swap (swap the members with `other`, let `other`'s destructor free the old array later) is also self-safe, at the cost of the old array living a little longer. ## What to test - A unit test that move-assigns an element to itself through a reference and then reads `size()`. - Run the suite under `-fsanitize=address`: the double-free variant fails immediately. - Do not rely on `-Wself-move`; it sees only the literal `x = std::move(x)`, not aliasing through indexes or references. ## Why the library allows it at all It would be simpler for everyone if self-move were simply forbidden, but the library cannot forbid what its own algorithms may do. Generic code that moves elements around inside one range, such as a `swap` of two positions that turn out to be the same, or a loop that moves `v[read]` to `v[write]` while both indexes still coincide, would need an extra comparison on every step to avoid it. Instead the standard makes the cheap promise, valid but unspecified, and requires element types to tolerate the case. Your types meet the same contract when you write the move assignment so that: - the object's invariants hold afterwards (pointer and size agree); - its destructor frees exactly what it still owns, and nothing twice; - a later assignment to it works normally. ## How far to go The bar is "valid", not "unchanged": a self-move that leaves the object empty meets the library's own standard. Preserving the value is a bonus that the ordering trick gives for free. What is never acceptable is a self-move that corrupts the object, because standard algorithms and `swap` may perform one.
- Why does std::swap(x, x) matter to a move assignment operator?In libc++, `std::swap` is `T t(std::move(x)); x = std::move(y); y = std::move(t);`. With both arguments the same object, the middle line is `x = std::move(x)` on an already moved-from `x`, then the last line restores the value. If the move assignment corrupts the object on self-move, a harmless-looking `swap(a[i], a[j])` with `i == j` breaks it.
- Is the if (this != &other) check a performance problem?Rarely. It is one pointer comparison that a branch predictor handles easily, since the self case is almost never taken. Detaching the source before freeing avoids even that branch and keeps the value on self-move, so it is a reasonable default for hand-written resource classes.
- Self-move-assignment is undefined behaviour, so a class need not handle it.
- The standard library guarantees a self-moved object keeps its value.
- -Wself-move catches every self-move, including ones through indexes.
- Using std::exchange in move assignment automatically makes it self-move safe.
- A self-move that empties the object violates the library's requirements.