2

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?

Zaki
  • 107
  • 9
  • 1
    not the cause of the error, but it looks wrong that only `Vector` can be copied to all other `Vector`s, for example you have no copy constructor for `Vector` but a conversion from `Vector` to `Vector`. I suppose you want `Vector(const Vector&);` rather than `Vector(const Vector&);` – 463035818_is_not_an_ai Nov 11 '22 at 13:12
  • I haven't paid attention to this. I created this class only to reproduce the error I am getting. – Zaki Nov 11 '22 at 13:27

1 Answers1

7

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);
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218