C++ c++;通过移动而不是复制来交换数组元素
是否可以通过简单地将数组的两个元素移动到新索引而不是使用临时值的昂贵副本来交换数组的两个元素 我有以下代码:C++ c++;通过移动而不是复制来交换数组元素,c++,arrays,C++,Arrays,是否可以通过简单地将数组的两个元素移动到新索引而不是使用临时值的昂贵副本来交换数组的两个元素 我有以下代码: struct Piece { int index; int type; int square; Piece() {} ~Piece() {} Piece(Piece& piece) { printf("copy"); } Piece(Piece&& piece) {
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;
}
结构件{
整数指数;
int型;
内景广场;
片段(){}
~Piece(){}
件(件&件){
printf(“副本”);
}
件(件和件){
printf(“移动”);
}
void运算符=(分段和分段){
printf(“copy1”);
内部温度=平方;
正方形=件。正方形;
件。方形=温度;
}
void运算符=(工件和工件){
printf(“move1”);
}
};
int main(){
件*件=新件[10];
工件*滑块=新工件[10];
块[0]={};
件[0],正方形=50;
件[1]={};
件[1],正方形=20;
工件温度=工件[0];
件[0]=件[1];
件[1]=温度;
选项1:使用std::swap
std::swap<Piece>(pieces[0], pieces[1])
此外,使移动操作不抛出。使用std::swap
std::swap(pieces[0], pieces[1]);
你可以等效地写:
Piece temp = std::move(pieces[0]);
pieces[0] = std::move(pieces[1]);
pieces[1] = std::move(temp);
但是std::swap
更为简洁。由于类的数据只是几个标量值,实际上,是否通过临时值交换它们并不重要。也就是说,如果放弃对打印代码的调用,或者优化编译,都无所谓。无论如何,这都将通过寄存器实现
不过你还是应该使用,因为这是一种“正确的方法”。如果你让你的作品类更具参与性,它实际上会产生一些效果
是否可以通过简单地将数组的两个元素移动到新索引而不是使用临时值的昂贵副本来交换数组的两个元素
不适用于给定的结构块。当您可以分配(复制、交换)时,您将受益于移动语义指向大数据量和/或已分配堆的指针。节省的成本来自于复制指针而不是较大的数据和/或避免内存释放/分配,这可能比复制大数据对象花费更多的CPU周期。为什么您认为这“成本高”?你有任何类型的数字来支持它吗?你认为软件太愚蠢而无法优化它吗?std::move()
实际上不应该为他的Piece类做任何事情。你不需要显式指定模板参数,编译器可以从输入参数推断出来:std::swap(pieces[0],pieces[1])
std::swap()
在可能的情况下使用移动语义。因此,如果Piece
支持移动,STL将根据选项2实现选项1。因此,在代码中始终支持选项1。
Piece temp = std::move(pieces[0]);
pieces[0] = std::move(pieces[1]);
pieces[1] = std::move(temp);