C++: Memory Leak;Vector-like class -


im beginnger in c++ , try creat container class similar vector. class should works vector type of data , used in range-based loop. wrote hpp tutor says there memory leak ,i think deleted dynamic memory,where problem?

#include "stdafx.h" using namespace std; template<class t> class customvector { public:     customvector();     ~customvector();     int size();     int free_capacity();     void add(t& temp);     int& operator[](int index);     void grow();      class iterator {         public:             iterator(t* ptr) : ptr(ptr) {}             iterator operator++() { iterator i(ptr); ++ptr; return i; }             bool operator!=(const iterator & other) { return ptr != other.ptr; }             const t& operator*() const { return *ptr; }          private:             t* ptr;         };      iterator begin() const { return iterator(&_elements[0]); }     iterator end() const { return iterator(&_elements[0]+_size); } private:     t*  _elements;     int _size;     int _capacity;     int default_capacity; };  template<class t> customvector<t>::customvector() {     default_capacity = 4;     _capacity = default_capacity;     _size = 0;     _elements = new t[_capacity];  } template<class t> customvector<t>::~customvector() {     delete[] _elements;  } template<class t> void customvector<t>::add(t& temp) {     grow(); //check if capacity full, if so,increase capacity default_capacity;     _elements[_size++]= temp;  } template<class t> int customvector<t>::size() {     return _size; }  template<class t> int customvector<t>::free_capacity() {     int free_c = _capacity - _size;     return free_c; }   template<class t> int& customvector<t>::operator[](int index) {     if (index<0 || index>_capacity)     {         cout << "index beyond limit" << endl;         return _elements[0];     };     return _elements[index]; }  template<class t    > void customvector<t>::grow()  {      if (_capacity == _size)      {         _capacity += default_capacity;         t* p = new t[_capacity];         std::copy(_elements, _elements + _size,p);         delete[] _elements;         _elements = p;     };  } 

the leaky case can find in grow:

    ...     t* p = new t[_capacity];     std::copy(_elements, _elements + _size,p); // may throw exception     delete[] _elements;     _elements = p;     ... 

if copying of contained element throws, _elements still points old array , new array pointed p leaks. can resolve unique_ptr:

std::unique_ptr<t[]> p(new t[_capacity]); std::copy(_elements, _elements + _size, p.get()); // it's ok if throws, unique_ptr take care of memory delete[] _elements; _elements = p.release(); 

using unique_ptr _elements simplify of code , improve correctness.


Comments

Popular posts from this blog

php - Invalid Cofiguration - yii\base\InvalidConfigException - Yii2 -

How to show in django cms breadcrumbs full path? -

ruby on rails - npm error: tunneling socket could not be established, cause=connect ETIMEDOUT -