delete 失败,求解。
代码如下。是想实现一个简单的vector。弄了一个下午。。delete那块老是出错。不知道为什么
#include<new>
#include<iostream>
using namespace std;
template<class Ty>
class my_vector
{
public:
typedef Ty* iterator;
typedef const Ty* const_iterator;
typedef Ty* point;
typedef const Ty* const_point;
typedef Ty& reference;
typedef const Ty& const_reference;
private:
iterator first;
iterator last;
iterator end_of_vec;
Ty* allocate_and_fill(size_t n, const Ty& value)
{
if (n < 0) n=0;
Ty* Ty_point = (Ty*) (operator new ((n+1) * sizeof(Ty)));
Ty* temp_point = Ty_point;
for ( ; n != 1; --n)
{
*Ty_point = value;
++Ty_point;
}
Ty_point = NULL;
return temp_point;
}
void fill_and_init(size_t n, Ty value)
{
first = allocate_and_fill(n, value)
last = (first + n);
end_of_vec = (first + n);
}
public:
my_vector():first(0),last(0),end_of_vec(0){}
my_vector(const size_t n, const Ty& value)
{
fill_and_init(n, value);
}
my_vector(size_t n)
{
fill_and_init(n, Ty());
}
size_t size() const
{
return begin == 0 ? 0 : last - first;
}
iterator begin() const
{
return first;
}
iterator end() const
{
return last;
}
size_t capacity() const
{
return first == 0 ? 0 : end_of_vec - first;
}
void push_back(const Ty& value)
{
if (last != end_of_vec)
{
*last = value;
++last;
}
else
{
insert(last, 1, value);
}
}
void insert(iterator iter,const size_t& num, const Ty value) //在某位置前面插入num个元素value
{
size_t temp_num = end_of_vec - last;
if (temp_num >= num && end() != 0) //没越界的情况
{
insert_aux(iter,num,value);
last = last + num;
}
else
{
size_t iter_flag = iter - first;
size_t n = size() + (num < size() ? size() : num);
point new_point = (point)(operator new ((n + 1) * sizeof(Ty))); //申请
copy_fill(first, last, new_point); //拷贝
size_t temp_size = size();
cout <<"cao" <<endl;
destroy(first);
first = new_point;
last = first + temp_size + num;
end_of_vec = first + n;
insert_aux((first + iter_flag), num, value);
}
}
protected:
void destroy(iterator iter)
{
if(iter != 0)
{
cout <<"ni" <<endl;
delete iter; //问题出在这里.改了又改。还是错的。删了程序可愿意运行,就是内存泄露
cout <<"ma" <<endl;
}
}
void copy_fill(iterator _first, iterator _last, iterator new_first) //拷贝区间内元素到新区间。返回拷贝后区间元素的最后位置之后
{
for ( ; _first != _last; ++_first)
{
*new_first = *_first;
++new_first;
}
}
void insert_aux(iterator iter, const size_t& num, const Ty&value)
{
iterator temp_iter = last; //记录last位置,第一个位置
for( ; temp_iter != iter; --temp_iter) //从最后一位开始向后移动num知道iter
{
*(temp_iter + num) = *temp_iter;
}
*(temp_iter + num) = *temp_iter;
for(int n = num ; n != 0; --n)
{
*iter = value;
++iter;
}
}
};
#include"my_vector.h"
#include<iostream>
using namespace std;
int main()
{
my_vector<int> vec;
vec.push_back(1);
cout <<vec.size() <<endl;
vec.push_back(2);
cout <<"aa" <<endl;
my_vector<int>::iterator iter = vec.begin();
cout <<*iter <<endl;
cout <<*(++iter) <<endl;
if(iter == vec.end())
{
cout <<"cao" <<endl;
}
cout <<"capcity" <<vec.capacity() <<endl;
cout <<vec.size() <<endl;
vec.push_back(3);
cout <<vec.size() <<endl;
return 0;
}
求解求解。。。