Is it possible to swap two elements of an array by simply moving both to the new index instead of a costly copy with a temp value?
I have this code:
struct Piece {
int index;
int type;
int square;
Piece() {}
~Piece() {}
Piece(Piece& piece) {
printf("copy");
}
Piece(Piece&& piece) {
printf("move");
}
void operator=(Piece& piece) {
printf("copy1");
int temp = square;
square = piece.square;
piece.square = temp;
}
void operator=(Piece&& piece) {
printf("move1");
}
};
int main() {
Piece* pieces = new Piece[10];
Piece* sliders = new Piece[10];
pieces[0] = {};
pieces[0].square = 50;
pieces[1] = {};
pieces[1].square = 20;
Piece temp = pieces[0];
pieces[0] = pieces[1];
pieces[1] = temp;
cout << pieces[1].square << " " << pieces[0].square;
char test;
cin >> test;
}
This always prints "move" when initializing and "copy1" when swapping with temp. Is there any way to do the same by moving, without using an array of pointers?
Please ignore the bad style of this code.
Use std::swap...
std::swap(pieces[0], pieces[1]);
You could equivalently write:
Piece temp = std::move(pieces[0]);
pieces[0] = std::move(pieces[1]);
pieces[1] = std::move(temp);
but std::swap is more concise.
Option 1: Use std::swap.
std::swap<Piece>(pieces[0], pieces[1])
Option 2: Use std::move.
Piece temp = std::move(pieces[0]);
pieces[0] = std::move(pieces[1]);
pieces[1] = std::move(temp);
Moreover, make your move operations non throwing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With