Making my own Vector. Whats wrong with it? [closed]
i am trying to make my own vector but i cant get it to work as i want. I get a error message on the Move-constructor it says: Exception thrown at 0x00007FF751A77ACC in auto-tests.exe: 0xC0000005: Access violation reading location 0xFFFFFFFFFFFFFFFF.
The first one got solved. But now i got the same error with another part of the code. The push_back finction, here is the code.
Here is the code for the move-constructor:
template<typename T>
inline Vector<T>::Vector(Vector&& other)
: m_nrOfElements(other.m_nrOfElements), m_capacity(other.m_capacity)
{
for (int i = 0; i < m_nrOfElements; i++)
{
m_elements[i] = other.m_elements[i]; /// HERE IS WHERE THE ERROR IS!
}
other.m_elements = nullptr;
other.m_capacity = 0;
other.m_nrOfElements = 0;
}
Solution 1:
You haven't allocated memory for m_elements
- and you shouldn't, since this is a move constructor. Just use std::exchange
to "steal" the pointer from other
and replace it with the value you desire - that is, nullptr
.
Example:
#include <utility>
template<typename T>
inline Vector<T>::Vector(Vector&& other)
: m_nrOfElements(std::exchange(other.m_nrOfElements, 0),
m_capacity(std::exchange(other.m_capacity, 0),
m_elements(std::exchange(other.m_elements, nullptr))
{
// constructor body can now be empty
}