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:

  1. Deallocating m_elements.
  2. Copying from other.m_elements to a destination pointer you've just deleted (invalid access).
  3. 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:

  1. Deallocate m_elements.
  2. 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;
}