i have an assignment to build a vector. The assignment have a huge testprogram, but the testprogram gives 0 information about memory leaks. At first i had an error message that said heap corruption detected but i think ive solved the problem with the last delete[] statement in this code:
template<typename T>
inline Vector<T>& Vector<T>::operator=(const Vector& other)
{
if (other.m_nrOfElements > m_nrOfElements)
{
delete[] m_elements;
m_capacity = other.m_capacity;
m_elements = new T[other.m_nrOfElements];
}
for (int i = 0; i < other.m_nrOfElements; i++)
{
m_elements[i] = other.m_elements[i];
}
m_nrOfElements = other.m_nrOfElements;
delete[] &other; //THIS LINE
return *this;
}
But when i run the program now, i get read access violation in my destructor instead. It looks like this:
template<typename T>
inline Vector<T>::~Vector()
{
delete[] m_elements;
}
And if i dont use the delete statement i get memory leaks. Is there any easy way to find memory leaks in Visual Studio 2022? As i said before, the assignment comes with a testprogram so i cant open the property page or anything like that.
Im posting the other constructors, operators and vaiables here under, if someone can find something that would help.
template <typename T>
class Vector
{
private:
int m_capacity;
int m_nrOfElements;
T* m_elements;
public:
template<typename T>
inline Vector<T>::Vector()
:m_nrOfElements(0),
m_capacity(5),
m_elements(new T[m_capacity])
{
}
template<typename T>
inline Vector<T>::Vector(const Vector& other)
:m_nrOfElements(other.m_nrOfElements),
m_capacity(other.m_capacity),
m_elements(new T[m_capacity])
{
for (int i = 0; i < other.m_nrOfElements; ++i)
{
m_elements[i] = other.m_elements[i];
}
}
template<typename T>
inline Vector<T>::Vector(int index, T element)
:m_nrOfElements(index),
m_capacity(index + 5),
m_elements(new T[m_capacity])
{
for (int i = 0; i < m_nrOfElements; ++i)
{
m_elements[i] = element;
}
}
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 = other.m_nrOfElements;
m_capacity = other.m_capacity;
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;
}
template<typename T>
inline T& Vector<T>::operator[](const int index) const
{
if ((index < 0) || (index >= m_nrOfElements))
{
throw std::exception("Index out of range");
}
return m_elements[index];
}