You're right, moving an int
is no different from copying it.
Here, std::move
only becomes useful only if T
's overloaded operator+
behaves differently for lvalues and rvalues.
I've never heard of such classes, but I guess it could be useful for dynamic arrays that overload +
in a clever way:
struct Vec
{
std::vector<int> elems;
};
// Returns a completely new vector.
Vec operator+(const Vec &a, const Vec &b)
{
assert(a.size() == b.size());
Vec ret(a.size());
for (std::size_t i = 0; i < a.size(); i++)
ret.elems[i] = a.elems[i] + b.elems[i];
return ret;
}
// Reuses storage of `a`.
Vec operator+(Vec &&a, const Vec &b)
{
assert(a.size() == b.size());
for (std::size_t i = 0; i < a.size(); i++)
a.elems[i] += b.elems[i];
return std::move(a);
}
// Reuses storage of `b`.
Vec operator+(const Vec &a, Vec &&b)
{
return std::move(b) + a;
}
// Reuses storage of `a`.
Vec operator+(Vec &&a, Vec &&b)
{
return std::move(a) + b;
}
Edit: apparently std::string
does a similar thing: its +
reuses storage of one of the operands, if possible. (Thanks @FrançoisAndrieux and @Artyer.)