I'm trying to make a struct box which has pointers to other boxes, and each box can contain some data as well, which in turn is also a struct. I create a new box and assign some values.
Now the problem is that delete doesn't seem to work on the box. I expect to read garbage after the delete, but I still get the same data that was there before the delete. I've added a destructor that prints a message so you can see if it is called. How is it possible that the destructor is called, but the data is still there?
It does seem to have something to do with the box containing pointers of its own type, because if I comment out the pointers in the box definition, the data content in the box is deleted as expected.
#include<iostream>
using namespace std;
typedef struct userdata{
int id;
double pi;
~userdata(){
cout<<"deleting userdata\n";
}
}userdata;
typedef struct box_t{
box_t* ptr1;
box_t* ptr2;
userdata data;
~box_t(){
cout<<"deleting box\n";
}
}box;
int main(int argc,char *argv[]){
box* ptr=new box;
ptr->data.id=19;
ptr->data.pi=3.14159;
cout<<ptr<<endl;
printf("data.id %i, data.pi %f\n",
ptr->data.id, ptr->data.pi
);
delete ptr;
cout<<ptr<<endl;
printf("data.id %i, data.pi %f\n",
ptr->data.id, ptr->data.pi
);
return 0;
}
Output:
0xc61530
data.id 19, data.pi 3.141590
deleting box
deleting userdata
0xc61530
data.id 19, data.pi 3.141590
Aucun commentaire:
Enregistrer un commentaire