如何在没有复制赋值运算符的情况下交换两个对象
How to swap two objects without copy assignment operator?
>我有一个A类,其中删除了复制赋值运算符。我应该如何交换 A 的两个实例?
我尝试使用std::swap
但没有奏效。
class A {
private:
int a;
public:
A& operator=(const A& other) = delete;
A(int _a = 0):a(_a){}
void showA() { std::cout << a << std::endl; }
};
int main()
{
A obj1(10);
A obj2(20);
obj1.showA();
obj2.showA();
//A temp;
//temp = obj1;
//obj1 = obj2;
//obj2 = temp;
obj1.showA();
obj2.showA();
}
我希望obj1
和obj2
互换。最初obj1.a
是10
,obj2.a
是20
,我希望obj1.a
20
,完成后obj2.a
10
。
如@Yksisarvinen所示,您需要定义移动构造函数和移动赋值才能使std::move
工作:
#include <iostream>
#include <utility>
class A {
private:
int a;
public:
A(int a_) : a(a_) {}
A(const A& other) = delete;
A& operator=(const A&) = delete;
A(A&& other) {
a = other.a;
}
A& operator=(A&& other) {
a = other.a;
return *this;
}
void showA() { std::cout << a << std::endl; }
};
int main(int argc, char* argv[]) {
A obj1(10);
A obj2(20);
obj1.showA();
obj2.showA();
std::swap(obj1, obj2);
std::cout << "swapped:" << std::endl;
obj1.showA();
obj2.showA();
return 0;
}
相关文章:
- 对象内部有大量数据容器,实现更高效的对象交换
- 错误试图在向量C 中交换卡对象
- 如何在C++中交换对象数组的 2 个不同对象
- 在多线程环境中交换C 地图对象
- 根据 C++ 中的特定数据交换这些对象
- 如何在没有复制赋值运算符的情况下交换两个对象
- C++ 为什么我不能在已删除的默认构造函数的对象上使用交换
- 交换对象不实现移动语义时的交换函数
- 交换两个 std::array<T、100> 对象的成本是多少?
- 使用交换对象自杀
- 交换对象本身
- 将对象交换到文件中
- 交换指针,删除第二个对象并创建指向第二个的新指针
- 使用复制和交换习惯用法,复制对象的析构函数如何不解除分配指向内存
- 如何在对象类型未知时实现交换函数
- 我应该清除作为参数传入的()容器,还是交换一个新对象
- 无法在C++中交换数组中的对象
- 同时交换char数组中的多个对象
- 如何在c++中快速交换列表和向量等容器中的对象
- 如何使用数组交换对象,c++.我想改变