Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading