Programs & Examples
Move Semantics · Study material
Counting copies and moves in matrix addition
operator+ takes its left operand by value. For x + y the parameter is a copy of x; for (x + y) + z it is the temporary result, which is moved in. The only copy is the unavoidable one.
#include <iostream>
#include <utility>
#include <vector>
class Matrix {
std::size_t n_;
std::vector<double> a_;
public:
static inline int copies = 0, moves = 0;
explicit Matrix(std::size_t n, double v = 0) : n_(n), a_(n * n, v) {}
Matrix(const Matrix& o) : n_(o.n_), a_(o.a_) { ++copies; }
Matrix(Matrix&& o) noexcept : n_(o.n_), a_(std::move(o.a_)) { ++moves; }
Matrix& operator=(const Matrix& o) { n_ = o.n_; a_ = o.a_; ++copies; return *this; }
Matrix& operator=(Matrix&& o) noexcept { n_ = o.n_; a_ = std::move(o.a_); ++moves; return *this; }
friend Matrix operator+(Matrix a, const Matrix& b) { // a is a copy OR a moved temporary
for (std::size_t i = 0; i < a.a_.size(); ++i) a.a_[i] += b.a_[i];
return a; // implicit move of the parameter
}
double at(std::size_t i, std::size_t j) const { return a_[i * n_ + j]; }
};
int main() {
Matrix x(300, 1), y(300, 2), z(300, 3);
Matrix sum = x + y + z; // (x + y) is a temporary, so the second + receives it by MOVE
std::cout << sum.at(0, 0) << " copies=" << Matrix::copies << " moves=" << Matrix::moves << '\n';
return 0;
}
6 copies=1 moves=2
A buffer class with all five special members
The rule-of-five example shows a deep copy, a stealing move and a move assignment that frees the old buffer first.
Forwarding arguments without losing rvalue-ness
The perfect-forwarding example compares a relay that turns everything into lvalues with one that uses std::forward.