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

问题描述 投票:1回答:1

我有一个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();
}

我希望交换obj1obj2。最初obj1.a10obj2.a20,我预计obj1.a20obj2.ato是10完成后。

c++ swap copy-assignment
1个回答
3
投票

正如@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;
}
© www.soinside.com 2019 - 2024. All rights reserved.