Home > Blockchain >  error use of deleted function when trying to pass rvalue to a tuple
error use of deleted function when trying to pass rvalue to a tuple

Time:11-12

Original context: I am trying to pass a tuple of (object, expected_value_of_some_property) to a test function

I created a simple class to reproduce the error I am facing:

template <typename T>
class Vector
{
private:
    size_t m_size;
    std::unique_ptr<std::vector<int>> m_vector;

public:
    Vector();
    Vector(const Vector<int>&);
    ~Vector() = default;

    void push_back(T);
    T get(int) const;
    size_t size() const;
};

template <typename T>
Vector<T>::Vector()
:m_size(0), 
m_vector(new std::vector<T>)
{}

template <typename T>
Vector<T>::Vector(const Vector<int>& v)
:m_size(v.size()), 
m_vector(new std::vector<T>)
{
    for (size_t i = 0; i < v.size(); i  )
    {
        this->push_back(v.get(i));
    }
}

template <typename T>
void Vector<T>::push_back(T value)
{
    m_vector->push_back(value);
    m_size   ;
}

template <typename T> 
T Vector<T>::get(int index) const
{
    return m_vector->operator[](index);
}

template <typename T> 
size_t Vector<T>::size() const
{
    return m_size;
}

The error is triggered when trying to produce a tuple of Vector object and an int somewhere in a test code:

int main(int argc, char const *argv[])
{
    std::tuple<Vector<int>, int> vector_test;

    vector_test = std::make_tuple(Vector<int>{}, 0);

    int size = std::get<0>(vector_test); 
    Vector<int> vector = std::get<1>(vector_test); 
    
    // .. test code

    return 0;
}

Output:

error: use of deleted function ‘std::tuple<Vector<int>, int>& std::tuple<Vector<int>, int>::operator=(const std::tuple<Vector<int>, int>&)’
   20 |     vector_test = std::make_tuple(Vector<int>{}, 0);
      |                                                   ^                                                          ^

What am I doing wrong here?

CodePudding user response:

Since your Vector class has a unique_ptr member, that means your class itself has the copy-assignment implicitly deleted. Therefore this assignment will fail

std::tuple<Vector<int>, int> vector_test;

vector_test = std::make_tuple(Vector<int>{}, 0);  // <--- this

Instead you can just directly initialize in one step

std::tuple<Vector<int>, int> vector_test = std::make_tuple(Vector<int>{}, 0);
  • Related