priority_queue的问题
priority_queue里放的是自定义的类,这个类又自己会分配空间。
但是跟踪看到重新建堆的时候,发现里面的指针被改变了!所以导致访问的时候出错。
例子如下:
#include <iostream>
#include <queue>
#include <cstring>
using namespace std;
class packet
{
public:
int len;
char *data;
public:
packet(const char* buf,int l)
:len(l),data(NULL)
{
data=new char[len];
cout<<"packet(buf,len): this="<<this<<" data="<<(void*)data<<endl;
memcpy(data,buf,len);
}
packet(const packet& p)
:len(p.len),data(NULL)
{
data=new char[len];
cout<<"packet(p): this="<<this<<" data="<<(void*)data<<" ";
p.pthis();
memcpy(data,p.data,len);
}
~packet()
{
cout<<"~packet(): this="<<this<<" data="<<(void*)data<<endl;
delete data;
}
void pthis() const
{
cout<<"pthis(): this="<<this<<" data="<<(void*)data<<endl;
}
friend bool operator<(const packet& p1, const packet& p2);
};
bool operator<(const packet& p1, const packet& p2)
{
return p1.len<p2.len;
}
int main()
{
priority_queue<packet> q;
q.push(packet("hello",5));
q.top().pthis();
}
执行结果为:
packet(buf,len): this=0x8047b70 data=0x8051ce8
packet(p): this=0x8053678 data=0x8051cf8 pthis(): this=0x8047b70 data=0x8051ce8
packet(p): this=0x8047ab0 data=0x8051d08 pthis(): this=0x8053678 data=0x8051cf8
~packet(): this=0x8047ab0 data=0x8051d08
~packet(): this=0x8047b70 data=0x8051ce8
pthis(): this=0x8053678 data=0x8051d08
~packet(): this=0x8053678 data=0x8051d08
也就是说
在push的时候元素是:packet(p): this=0x8053678 data=0x8051cf8
最后在queue里top()的元素是:pthis(): this=0x8053678 data=0x8051d08
data指针怎么会变化呢?