jeudi 10 septembre 2020

Error "function ... cannot be referenced -- it is a deleted function" using instance of class with a std::vector of std::unique_ptr

So I have a class (highly simplified and altered to showcase error)

class OData
{
public:

    // The error-generating members.
    std::vector<std::unique_ptr<Sample_Object>> old_samples;
    std::vector<std::unique_ptr<Sample_Object>> new_samples;


    OData() = default;

    ~OData() = default;

};

which is used by a class

class OManager
{
private:
    OData data;

public:

    OManager() {}

    void do_work();

and the Sample_Object

class Sample_Object
{
private:
    // A bunch of member variables of different kind, but not of pointer-type
    
    // These are just example member variables
    double var1, var2;
public:

    Sample_Object() = default;

    Sample_Object(const double var1, const double var2) : var1(var1), var2(var2) {};

    Sample_Object(const Sample_Object &to) = default;

    Sample_Object(Sample_Object &&to) = default;

    ~Sample_Object() = default;

    Sample_Object& operator=(const Sample_Object &rhs) = default;

    Sample_Object& operator=(Sample_Object &&rhs) = default;

    // Extra functions neglected here..
};

Now, in the OManager class, in the do_work() function, attempt to do some transfer of data from the old_samples vector to the new_samples vector as in

void OManager::do_work()
{
    data.new_samples.clear();

    // Here, some calculations are done, but in this example replaced with the simple set of these two variables.
    double var1(0.0), var2(0.0);

    data.new_samples.push_back(std::move(std::unique_ptr<Sample_Object>(new Sample_Object(var1, var2))));

    // After the calculations, the newly set data in new_samples are copied over to the old_samples:
    data.old_samples.resize(data.new_samples.size());
    for (size_t i = 0; i < data.new_samples.size(); i++)
    {
        data.old_samples[i].reset(new Sample_Object(*(data.new_samples[i])));
    }   
}

however, this code type gives me

/usr/include/c++/7/bits/stl_construct.h(75): error: function "std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp> &) [with _Tp=Sample_Object, _Dp=std::default_delete<Sample_Object>]" /usr/include/c++/7/bits/unique_ptr.h(383): here cannot be referenced -- it is a deleted function

and I have not yet found a solution despite endless efforts. Do any of you see what is wrong here?

I have also attempted to use std::vector<Sample_Object> instead, but this has given me errors of the type std::length_error with the push_back operation allocating an "endless" vector (although this might be due to other external causes in my project/library).

Aucun commentaire:

Enregistrer un commentaire