Good day. There is the following class with the implementation of rule 3, more precisely 4:

#include <assert.h> #include <algorithm> template<typename T> class Array { public: //constructor Array(const size_t size = 0) : m_size(size) , m_array(m_size ? new T[m_size]() : nullptr) {} //destructor ~Array() { delete[] m_array; } friend void swap(Array& first, Array& second) { using std::swap; swap(first.m_size, second.m_size); swap(first.m_array, second.m_array); } size_t size() const { return m_size; } T& operator [](const size_t index) { assert(index < m_size); return m_array[index]; } //move-construct Array(Array&& other) : Array() { swap(*this, other); } //copy-constructor Array(const Array& other) : m_size(other.m_size), m_array(m_size ? new T[m_size] : nullptr) { std::copy(other.m_array, other.m_array + m_size, m_array); } //copy-assignment Array& operator=(Array other) { swap(*this, other); return *this; } private: size_t m_size; T* m_array; }; 

According to the assignment, it was necessary to add the implementation of the copy constructor, the move constructor, the assignment operator, which was done, and the “Designed class should give a strict guarantee of exceptions safety”, which seems to satisfy the rule. But when sending for verification, I get the message: "A memory leak is possible in the implementation of the array." Help localize.

  • format the code, in this form it is impossible to read - user227465

1 answer 1

The copy constructor copies the elements from another array. If the class assignment copying operator T throws an exception, then the memory allocated for this array will leak (and the already created array elements will not be destroyed, potentially creating even more leaks).

The assignment copy operator must take Array const & as input, and Array && which is moving, and you have neither fish nor meat (although this may be the case for the task).

  • Can you explain how to fix this leak? - Totem
  • 2
    @ProstoNekitos The main problem with copy-and-swap is the overhead from the simultaneous existence of 3 objects when copying. Leakage is easily unique_ptr using a smart pointer unique_ptr instead of a raw pointer. - VTT
  • This task is from the online platform Stepik, there it will not be possible to use them, at least in this task - Totem
  • @ProstoNekitos Why not? The standard library is also there. - VTT
  • It will not work because of the organization of the task, all that is available to me is just adding my own methods (copying, assigning, moving) to the finished class - Totem