C ++:内存泄漏;类似矢量的类

时间:2015-10-22 14:21:42

标签: c++ vector memory-leaks

我是C ++的初学者,并尝试创建类似于Vector的容器类。对于所有类型的数据,此类应该像Vector一样工作,并且可以在基于范围的for循环中使用。 我写了hpp,但是我的导师说有内存泄漏,我想我删除了所有的动态内存,可能是哪个问题?

#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 the capacity is full, if so,increase capacity by 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;
    };

}

1 个答案:

答案 0 :(得分:3)

我能找到的唯一漏洞案例是grow

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

如果复制所包含的元素,则_elements仍然指向旧数组,p指向的新数组会泄漏。您可以使用unique_ptr解决此问题:

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

unique_ptr使用_elements也可以简化部分代码并提高正确性。