为什么重载的delete运算符未被vector调用?
下面是我写的为试验重载new、delete 运算符写的一个小程序
可是从输出的结果看,delete运算符在vector中却一直未被调用,可程序最后一行却显示delete可以运行,这是为什么?请各位大虾帮忙!
运行环境:
rh 6.2
kernel 2.4
gcc 2.95.3
stlport 4.0
//-------------------------------------------------------
// Example test new & delete operator
//
#include <iostream>
#include <vector>
#include <cstddef>
#include <new>
using namespace std;
class Packet
{
public:
static const int BUFF_SIZE = 2048;
static const int BUFF_NUM = 100;
Packet(){}
Packet(const Packet& r){ memmove(_buff,r._buff,BUFF_SIZE); }
~Packet() {}
const char* getbuff() const {return _buff;}
void setbuff(char* r){ memmove(_buff,r,BUFF_SIZE); }
void operator=(const Packet& r) { memmove(_buff,r._buff,BUFF_SIZE); }
static void* operator new(size_t) throw(bad_alloc);
static void* operator new(size_t,Packet* &addr) throw(bad_alloc);
static void operator delete(void*) throw();
private:
char _buff[BUFF_SIZE];
static char pool[];
static bool pool_idx[];
static int _num;
};
char Packet::pool[Packet::BUFF_NUM * sizeof(Packet)];
bool Packet::pool_idx[Packet::BUFF_NUM];
int Packet::_num = 0;
void* Packet::operator new(size_t) throw(bad_alloc)
{
for (int p = 0; p < Packet::BUFF_NUM; p++)
{
if (!pool_idx[p])
{
_num++;cout << "[newx] = " << _num << " ";
pool_idx[p] = true;
return pool+p*sizeof(Packet);
}
}
throw bad_alloc();
}
void* Packet::operator new(size_t,Packet* &addr) throw(bad_alloc)
{
for (int p = 0; p < Packet::BUFF_NUM; p++)
{
if (!pool_idx[p])
{
_num++;cout << "[new] = " << _num << " ";
pool_idx[p] = true;
void* pt = pool+p*sizeof(Packet);
memmove(pt,addr,sizeof(Packet));
return pt;
}
}
throw bad_alloc();
}
void Packet::operator delete(void* p) throw()
{
if (p != 0){
_num--;cout << "[del] = " << _num << " ";
pool_idx[((char*)p - pool) / sizeof(Packet)] = false;
}
}
void main()
{
int iNum = 0;
cout << "input num:"; // 0 < num < 75,it's no problem, but num>75....
cin >> iNum;
vector<Packet> v;
for (int i = 0; i<10; i++)
{
v.push_back(Packet());
}
for (int i = 0; i<iNum; i++)
{
v.push_back(Packet());
v.erase(v.begin()); //why delete operator is not called?
}
delete new Packet; //it's ok,delete is called
}