Home > Net >  Copy assignment operator with non-copyable members
Copy assignment operator with non-copyable members

Time:10-05

Say I have a class A with only a constructor:

struct A
{
    A() = default;
    A(const A&) = delete;
    A& operator=(const A&) = delete;
};

I also have a class B which contains an instance of A and defines the copy constructor as follows:

struct B
{
    B() = default;
    B(const B& other) : _a{} {}
    A _a;
};

The constructor of B here simply initializes _a with a new instance of A. But, how could I write the assignment operator for B (since I can't "reinitialize" _a)?

CodePudding user response:

If you want operator= to create a fresh new A similar to the copy constructor and if dynamic allocation is feasible you can use a std::unique_ptr<A> as member:

struct A
{
    A() = default;
    A(const A&) = delete;
    A& operator=(const A&) = delete;
};

struct B
{
    B() : _a{std::make_unique<A>()} {}
    B(const B& other) : _a{std::make_unique<A>()} {}
    B& operator=(const B& other) {
        _a = std::make_unique<A>();
        return *this;
    }
    std::unique_ptr<A> _a;
};

Though, if B has a non-copyable (non-movable) member, then the least surprise would be if B is also non-copyable (non-moveable).

CodePudding user response:

According to the definition of class A, an instance of A is non-copyable and also non-moveable. Therefore, I accepted the answer of @463035818_is_not_a_number.

Here is another answer which assumes that A can be made moveable, just for completeness or in case it may be useful to somebody.

struct A
{
    A() = default;
    A(const A&) = delete;
    A& operator=(const A&) = delete;
    A(A&&) = default;
    A& operator=(A&&) = default;
};

struct B
{
    B() = default;
    B(const B&) : _a{} {}
    B& operator=(B other)
    {
        std::swap(_a, other._a);
        return *this;
    }
    A _a;
};
  • Related