For a C++ Buffer class that owns a heap array, how do you write its move constructor and move assignment operator?
answer
- take the resource, then disarm
- the source's destructor still runs
- assignment frees the old array
- std::exchange, noexcept
basics
~20 sThe move constructor copies the source's pointer and size, then sets the source to nullptr and 0 so its destructor frees nothing. Move assignment also frees its own array first and survives self-move. Both are noexcept.
solid answer
~40 sA move takes the resource instead of duplicating it. The move constructor copies `other.data_` and `other.size_` into the new object, then resets the source to `nullptr` and `0`; the reset matters because the source's destructor still runs and would `delete[]` the same array again. `std::exchange(other.data_, nullptr)` does the read and the reset in one expression. Move assignment has two extra duties: the target already owns an array, so it must `delete[]` that before adopting the incoming one, and it must survive `x = std::move(x)`, either with an `if (this != &other)` guard or by detaching the source before freeing. Both operations only move pointers and cannot fail, so declare them `noexcept`.
code
cpp · 30 lines#include <cstddef>
#include <cstdio>
#include <utility>
class Buffer {
public:
explicit Buffer(std::size_t n) : size_(n), data_(new float[n]{}) {}
~Buffer() { delete[] data_; }
Buffer(Buffer&& other) noexcept
: size_(std::exchange(other.size_, 0)), data_(std::exchange(other.data_, nullptr)) {}
Buffer& operator=(Buffer&& other) noexcept {
if (this != &other) {
delete[] data_;
size_ = std::exchange(other.size_, 0);
data_ = std::exchange(other.data_, nullptr);
}
return *this;
}
std::size_t size() const { return size_; }
private:
std::size_t size_;
float* data_;
};
int main() {
Buffer terrain(4096);
Buffer staged = std::move(terrain); // move construction
Buffer slot(16);
slot = std::move(staged); // move assignment frees slot's old array
std::printf("terrain=%zu staged=%zu slot=%zu\n", terrain.size(), staged.size(), slot.size());
}go deeper
Recall the two steps: take the pointer and size, then set the source to nullptr and 0 so its destructor does not free the array a second time.
Explain why assignment must free the target's old array, why the order or a guard makes self-move safe, and why both members are noexcept.
Diagnose a double free or a leak from a hand-written move, and argue for the rule of zero: a std::vector<float> or std::unique_ptr<float[]> member makes these members unnecessary.
Weigh hand-written resource classes against composing standard owners; keep the few hand-written ones small, noexcept and covered by sanitizer runs.
## What a move owes its source A **move constructor** (`Buffer(Buffer&& other)`) and a **move assignment operator** (`Buffer& operator=(Buffer&& other)`) are ordinary member functions selected when the argument is an rvalue. Nothing in the language transfers the resource for you: whatever the body does is the move. Two facts shape that body: - the source object is **still alive** after the move, and its destructor will run later; - the source must be left **valid**: its invariants hold, so the destructor, assignment and any member without a precondition still work. For a `Buffer` with `std::size_t size_` and `float* data_`, the cheapest valid state for a source is "empty": `data_ == nullptr` and `size_ == 0`. `delete[] nullptr` does nothing, so the destructor needs no special case. ## The move constructor, step by step 1. Initialise `size_` from `other.size_` and `data_` from `other.data_`, taking the pointer, not the floats. 2. Set `other.data_ = nullptr` and `other.size_ = 0`, so `other`'s destructor frees nothing and `other.size()` agrees with its pointer. 3. Declare it `noexcept`: copying a pointer and an integer cannot throw. `std::exchange(obj, new_value)` (in `<utility>` since C++14) returns the old value of `obj` and stores the new one, so `data_(std::exchange(other.data_, nullptr))` does steps 1 and 2 for one member in a member initializer. ## The move assignment operator Assignment differs from construction because the target already owns an array. 1. Detach the incoming resource from `other` (take its pointer and size, leave it empty). 2. `delete[]` the array the target owned before. 3. Store the incoming pointer and size, and return `*this`. Writing it in that order is also **self-move safe**: if `other` is `*this`, step 1 empties the object, step 2 deletes a null pointer, and step 3 puts the original array back. The other common form keeps "free first, then take" and wraps it in `if (this != &other)`. | Form | Self-move safe | Cost | |---|---|---| | `if (this != &other) { delete[] data_; take; }` | yes, by the guard | one comparison | | detach from `other` first, then `delete[]` the old array | yes, by ordering | none extra | | move-and-swap (swap members, let `other`'s destructor free the old array) | yes | the old array lives until `other` is destroyed | ## Mistakes that compile - **Not resetting the source.** Both destructors `delete[]` the same pointer: a double free, which AddressSanitizer reports at the second destructor. - **Not freeing the target's old array** in assignment: a leak on every move-assignment. - **Leaving `size_` non-zero with `data_` null.** The destructor is fine, but `size()` now lies and a loop over the elements dereferences null; that breaks the "valid" half of the contract. - **Taking `const Buffer&&`.** A const rvalue reference cannot be modified, so the source cannot be reset; the function is a copy in disguise. - **Forgetting `noexcept`.** The code is correct, but `std::vector` copies such elements when it reallocates, which turns a cheap move into an allocation per element. - **`std::move` on the raw pointer.** `data_(std::move(other.data_))` copies the pointer and leaves the source unchanged; moving a raw pointer is a copy. ## Testing the pair A hand-written move pair deserves a small test that a sanitizer run makes decisive: 1. Move-construct from a full `Buffer` and check that the source reports `size() == 0` and the target the old size. 2. Move-assign into a `Buffer` that already owns an array; under `-fsanitize=address` a missing reset shows up as a double free, and a missing `delete[]` as a leak report at exit where leak detection is on (the default on Linux; `ASAN_OPTIONS=detect_leaks=1` elsewhere). 3. Move-assign an element to itself through a reference and check it is still usable. 4. Add `static_assert(std::is_nothrow_move_constructible_v<Buffer>);` so the `noexcept` cannot be lost silently. The simplest way to avoid all of this is not to write the pair at all: a `std::vector<float>` or `std::unique_ptr<float[]>` member already has correct, `noexcept` moves. ## Where neighbouring rules take over Whether the compiler would declare these members itself, and when declaring a destructor or copy operation suppresses them, belongs with the rule of zero, three and five; the exact exception-safety guarantees are covered with exception safety. The point here is the body: take the resource, leave the source empty and consistent, free what the target held, and mark the pair `noexcept`.
- Why not write data_(std::move(other.data_)) in the move constructor?Because moving a raw pointer is a copy: `std::move` only casts, and a `float*` has no move constructor that resets the source. `other.data_` keeps pointing at the array, so both destructors `delete[]` it. Use `std::exchange(other.data_, nullptr)`, or assign `nullptr` explicitly in the body.
- Should the moved-from Buffer be empty, or may it keep some array of its own?Any state works if its invariants hold: the destructor, assignment and `size()` must all behave. Empty (`nullptr`, 0) is the usual choice because it costs nothing and needs no allocation, which also keeps the move `noexcept`. Allocating a fresh small array for the source would make the move able to throw.
- The compiler automatically nulls the source's pointer after a move constructor runs.
- A moved-from object's destructor is skipped, so resetting the source is optional.
- std::move on a raw pointer member transfers ownership and nulls the original.
- Move assignment can just overwrite data_ because the old array belongs to the source.
- A move constructor should take const Buffer&& so it cannot damage the source.