Suppose I have class like this one:
struct A{
std::string a;
std::string b;
std::string c;
std::string d;
};
If I use std::swap
, it probably will do something like this:
// pseudo-code:
void std::swap(A &a, A &b){
A tmp = std::move(a);
a = std::move(b);
b = std::move(tmp);
}
It will construct "empty" object tmp
using default c-tor - generally cheap operation. Then it hopefully move 3 times, except in crazy cases when move decay to copy.
However if i do my own swap:
void swap(A &a, A &b){
std::swap(a.a, b.a);
std::swap(a.b, b.b);
std::swap(a.c, b.c);
std::swap(a.d, b.d);
}
It definitely will use less memory, but it still need to construct empty std::string
- 4 times !!!
I could go wild, and make it with single std::string
.
In all cases it does not look like big improvement.
Only proper case I could think of is if default c-tor is ridiculously expensive. Am I correct?