Search code examples
c++swapcopy-assignment

How to swap two objects without copy assignment operator?


I have a class A where, the copy assignment operator is deleted. How should I swap two instances of A ?

I tried using std::swap but that did not work.

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();
}

I expect obj1 and obj2 to be swapped. Initially obj1.a is 10 and obj2.a is 20, I expect obj1.a to be 20 and obj2.ato be 10 when done.


Solution

  • As @Yksisarvinen indicated you need to have move constructor and move assignment defined in order to get std::move to work:

    #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;
    }