Topics / C++ for Embedded / Q5
What are move semantics and why do they matter even without a heap?
Short answer: Move semantics (C++11) let an object transfer ownership of its resources to another object instead of copying them. A move constructor / move assignment takes an rvalue reference (T&&), steals the source's resource, and leaves the source in a valid but empty state. std::move is just a cast that says "this object may be moved from". On embedded systems, moves matter mostly for unique ownership types: a buffer handle from a pool, a DMA channel or a file descriptor that must have exactly one owner, can be returned from functions and stored in containers without copying or double release.
#include <cstdio>
#include <utility>
class PoolBuffer {
public:
explicit PoolBuffer(int idx) : idx_(idx) { std::printf("take %d\n", idx_); }
~PoolBuffer() { if (idx_ >= 0) std::printf("give %d\n", idx_); } // return to the pool
PoolBuffer(const PoolBuffer &) = delete; // one owner only
PoolBuffer &operator=(const PoolBuffer &) = delete;
PoolBuffer(PoolBuffer &&o) noexcept : idx_(o.idx_) { o.idx_ = -1; } // steal
PoolBuffer &operator=(PoolBuffer &&o) noexcept {
if (this != &o) { if (idx_ >= 0) std::printf("give %d\n", idx_); idx_ = o.idx_; o.idx_ = -1; }
return *this;
}
int index() const { return idx_; }
private:
int idx_;
};
PoolBuffer acquire() { return PoolBuffer(3); } // returned without copying (guaranteed elision)
int main()
{
PoolBuffer a = acquire();
PoolBuffer b = std::move(a); // ownership moves; a is now empty
std::printf("a=%d b=%d\n", a.index(), b.index());
} // prints "give 3" exactly once
Key rules
- Rule of zero: prefer members that already manage themselves (
std::array,std::unique_ptr), so you write no special members at all. - Rule of five: if you write a destructor, copy constructor/assignment or move constructor/assignment, think about all five.
- Mark moves
noexcept(containers rely on it). - Copy elision: returning a local or a temporary usually constructs it directly in the caller (guaranteed for prvalues since C++17).
- Using an object after
std::moveis legal only for operations that don't assume a value (assign, destroy).