Search code examples
c++visual-studio-2019move-semanticsassignment-operatordeleted-functions

How do I assign an object containing an unique_ptr to a vector of its type when a move assignment operator is defined?


The self-contained program section below leads to this error on Visual Studio 2019:

"function "partition_data::operator=(const partition_data &)" (implicitly declared)" is a deleted function.

Based on research around this type of problem I have defined a move assignment operator because of the unique_ptr but I still get the above error. How can I resolve this error in this example?

#include <cstddef>
#include <memory>
#include <utility>
#include <vector>

struct partition_data
{
public:
    partition_data(std::size_t size, double initial_value)
        : data_(new double[size])
        , size_(size)
    {
        for (std::size_t i = 0; i < size; ++i)
            data_[i] = initial_value;
    }

    partition_data& operator=(partition_data&& other){
        data_ = (std::move(other.data_));
        size_ = other.size_;
    }

    partition_data(partition_data&& other) noexcept
        : data_(std::move(other.data_))
        , size_(other.size_)
    {
    }

private:
    std::unique_ptr<double[]> data_;
    std::size_t size_;
};


int main()
{

    partition_data A = partition_data(5, 0.1);
    partition_data B = partition_data(5, 0.2);
    std::vector<partition_data> V(2);
    V[0] = A;  //here occurs the error
    V[1] = B; //here occurs the error
}

Solution

  • You have to move your object:

    V[0] = std::move(A);
    V[1] = std::move(B);
    

    or even construct in place

    std::vector<partition_data> V;
    V.reserve(2);
    V.emplace_back(5, 0.1);
    V.emplace_back(5, 0.2);