我目前正在使用 Accelerated C++,我正在尝试在 CH11 中创建我的版本。当尝试通过析构函数释放内存时,无论我创建一个空的“Vec”还是使用推回的一个,我都会获得读取访问内存。我不确定我错过了什么。谢谢你的帮助。
#include "Vec.h"
int main()
{
Vec<int> v;
return 0;
}
/////////
#include <algorithm>
#include <cstddef>
#include <memory>
using std::max;
/////////////////////////////
template <class T> class Vec {
public:
typedef T* iterator;
typedef const T* const_iterator;
typedef size_t size_type;
typedef T value_type;
typedef T& reference;
typedef const T& const_reference;
//Constructor
Vec() { create();}
explicit Vec(size_type n, const T& = T()) {create(n,t);}
//Copy
Vec(const Vec& v) {create(v.begin(), v.end());}
//Assignment
Vec& operator=(const Vec&);
//Destructor
~Vec() { uncreate();}
//Indexing
T& operator[](size_type i) {return data[i]; }
const T& operator[](size_type i) const { return data[i]; }
//Size
size_type size() const { return avail - data; }
//Return member variables
iterator begin() { return data; }
const_iterator begin() const { return data; }
iterator end() { return avail; }
const_iterator end() const {return avail; }
//Uncreate
void clear() { uncreate(); }
//Check empty
bool empty() const { return data == avail; }
//////////////////////
private:
iterator data; //first
iterator avail; //(one past) last element
iterator limit; //(one past) allocated memory
std::allocator<T> alloc; // object for memory allocation
//allocate and initialize thorugh constructors
void create();
void create( size_type, const T&);
void create(const_iterator, const_iterator);
//destory
void uncreate();
};
////////////////////////////
template <class T> void Vec<T>::create()
{
data = avail = limit;
}
template <class T> void Vec<T>::create(size_type n, const T& val)
{
data = alloc.allocate(n , 0);
limit = avail = data + n;
std::uninitialized_fill(data, limit, val);
}
template <class T> void Vec<T>::create(const_iterator i, const_iterator j)
{
data = alloc.allocate(j - i, 0);
limit = avail = std::uninitialized_copy(i , j, data);
}
template <class T> void Vec<T>::uncreate()
{
if(data) {
iterator it = avail;
while(it != data)
alloc.destroy(--it);
alloc.deallocate(data, limit - data);
}
data = limit = avail = 0;
}