c++memorysmart-pointersraii

Swapping private unique pointers with a public method


I have a class with a private unique_ptr member and I want to expose a public swap function which will swap ownership of its unique_ptr member with that of the provided other. How can I do so?

class A{ // a is polymorphic type, derivatives A1, A2, etc
    private:
        unique_ptr<B> b;
    public:
        void swap_b(A??? other) {
            A.b.swap_c(other.b) // I want to swap A.b.c with other.b.c
        }
};

class B{ // b is polymorphic type
    private:
        unique_ptr<C> c; // c is also polymorphic type
    public:
        void swap_C(B??? other) {
            B.c.swap(other.c)
        }
};

int main() {
    unique_ptr<A> alphaOne = make_unique<A1>(...);
    unique_ptr<A> alphaTwo = make_unique<A2>(...);
    alphaOne.swap(alphaTwo); // the unique_ptr alphaOne.b.c should swap ownership with alphaTwo.b.c
}

I have a vector<unique_ptr<A>>, from which I want to grab any two elements and call swap on them to swap their b.c unique_ptrs. How can I achieve this?


Solution

  • I am unsure if I am missing something, but a simple reference should suffice:

    #include <memory>
    using namespace std;
    
    class C {};
    
    class B {
       private:
        unique_ptr<C> c;
    
       public:
        void swap(B& other){ c.swap(other.c); }
    };
    
    class A {
       private:
        unique_ptr<B> b;
    
       public:
        virtual ~A() = default; // See note 1.
    
        void swap(A& other){ b.swap(other.b); }
    };
    
    class A1:public A{};
    class A2:public A{};
    
    
    int main() {
        unique_ptr<A> alphaOne = make_unique<A1>();
        unique_ptr<A> alphaTwo = make_unique<A2>();
        alphaOne.swap(alphaTwo);
    }
    
    1. The destructor of the base class should be virtual when you destroy instances via a base class pointer.