user6386155 user6386155 - 3 months ago 17
C++ Question

Move assignment/construct in C++

Consider

class A
{
array<double, 10> array;
double &a5;

public:
A():a5(array.at(5))
{}

};


It feels like the move assignment or move constructor on this class would make the member
a5
invalid. Is that correct? Is there a workaround?

Answer

To avoid any possibility of a5 becoming invalid, implement your own move constructor/assignment to copy/move the array content but not change a5, eg:

class A
{
    std::array<double, 10> arr;
    double &a5;

    A()
      : a5(arr[5])
    {}

    A(const A& src)
      : arr(src.arr), a5(arr[5])
    {}

    A(A&& src)
      : arr(std::move(src.arr)), a5(arr[5])
    {}

    A& operator=(const A& rhs)
    {
        if (this != &rhs)
            arr = src.arr;
        return *this;
    }

    A& operator=(A&& rhs)
    {
        std:swap(arr, src.arr);
        return *this;
    }
};
Comments