How do i get rid of heap corruption detected. Class Vector
Solution 1:
As @jo-art commented, your move constructor seems OK; however, the move assignment operator is:
- Deallocating
m_elements
. - Copying from
other.m_elements
to a destination pointer you've just deleted (invalid access). - Setting
other.m_elements
to nullptr without deallocating it first (memory leak).
delete[] m_elements;
m_nrOfElements = other.m_nrOfElements;
m_capacity = other.m_capacity;
for (int i = 0; i < other.size(); i++)
{
m_elements[i] = other.m_elements[i];
}
other.m_elements = nullptr;
other.m_capacity = 0;
other.m_nrOfElements = 0;
Instead:
- Deallocate
m_elements
. - Move the data from
other
as you do at the move constructor.
[Demo]
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))
{
}
template<typename T>
inline Vector<T>& Vector<T>::operator=(Vector&& other)
{
delete[] m_elements;
m_nrOfElements = std::exchange(other.m_nrOfElements, 0);
m_capacity = std::exchange(other.m_capacity, 0);
m_elements = std::exchange(other.m_elements, nullptr);
return *this;
}