samedi 23 juillet 2016

Is there way for not to call the destructor two times? (C++)

I have a class (named layer32) which has a member field as an array of numbers (named raster). The size of the array depends on an other member filed (named npixels) which gets value at the initialization of the object.

I want to call the destructor manually, which releases the memory allocated for the array raster by

delete[] raster;

However, somewhere after the manual destructor call, there is an automatic call of the destructor which tries to achieve again

delete[] raster;

which results fatal error of course. My question is, that is there any way to disable the second, automatic call of the destructor?

PS: other SO Q&A-s revealed, that calling destructor manually especially when the destructor contains delete[] is not the best way of programming (to say the least). I know. But I wish to know the answer to my question (at least because of curiosity).

//...
class layer32{
 public: uint32* raster;

 public: layer32(int npixels){
  raster=new uint32[npixels];
  for(int i=0;i<npixels;i++){
   raster[i]=0;
  }
 }
 public: ~layer32(){
  delete[] raster;
 }
}

int main(){
 //...
 layer32* birka;
 for(int i=0;i<65536;i++){
  birka = new layer32(i+1);
  //...
  delete birka;
  //...
 }
 //...
 return 0;
}

Aucun commentaire:

Enregistrer un commentaire