Search code examples
c++movedeleted-functions

C2280 error attempint to reference a deleted function


The function DataContainer.initial() triggers a C2280 error. After defining a move assignment operator it works. But I am not clear why in function initial_2() it works. The obvious difference is that data_a is a local variable and data_b is a class member. Thanks for helping.

#include <vector>
#include <iostream>

class DataTypeA
{
    std::vector<double> data;
public:
    // default constructor
    DataTypeA() {}

    // Move constructor
    DataTypeA(DataTypeA&& rhs) noexcept :data(std::move(rhs.data))
    {
        std::cout << __FUNCTION__ << std::endl;
    }

    //DataTypeA& operator=(TypeB&& rhs) noexcept
    //{
    //  data = (std::move(rhs.data));
    //  return *this;
    //}

    DataTypeA(size_t width, size_t height, double default_val)  { data.resize(width * height, default_val); }

    size_t get_size() const { return data.size(); }
};

class Reader 
{
public:
    Reader() {}

    DataTypeA read_data()
    {
        DataTypeA rtn(5, 5, 1.2);
        return rtn;
    }
};

class DataContainer
{
    DataTypeA data_b;
public:
    DataContainer() {}

    void initial()
    {
        Reader rd;
        
        // this requires the copy or move assignment operator
        // Error C2280  'DataTypeA &DataTypeA::operator =(const DataTypeA &)': attempting to reference a deleted function   
        data_b = rd.read_data();
    }

    void initial_2()
    {
        Reader rd;
        DataTypeA data_a = rd.read_data();
        std::cout << data_a.get_size();
    }
};

Solution

  • In the function initial_2, you are creating a new object of type DataTypeA from an existing object, so you can use the move constructor. However, in initial, you are assigning new data to an existing object. For this, you need to have the assignment operator. See Difference between the move assignment operator and move constructor?.