如何在没有复制赋值运算符的情况下交换两个对象?

How to swap two objects without copy assignment operator?

我有一个class一个where,复制赋值运算符被删除了。我应该如何交换 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();
}

我希望 obj1obj2 可以互换。最初 obj1.a10obj2.a20,我希望 obj1.a20obj2.a10 完成后。

正如@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;
}