简体   繁体   中英

Why do I have created a potential stray pointer when having delete in the destructor here?

My program crashes upon exit. Tracing the error back I arrived at the destructor of the class gWSW. Here is the problem:

I have a class gShop: public gTexture. In this class I declare and initializes a pointer to an object of the class gWSW.

In gWSW I have again a pointer to an object declared and initialized of the class gTexture.

I have given every class the proper destructor with calling delete on the pointers.

The programm runs fine until I press ESC and all the desctuctors are called. Here it crashes in the destructor of gWSW. That is I have something like that:

class gShop : public gTexture
   {
   public:
       gShop(): pWSW(new gWSW()) {}
      ~gShop(){delete pWSW;}   

   gWSW*    pWSW;
   };

class gWSW 
   {
   public:
       gWSW():gWSW: pTextuer(new gTexture()) {}
      ~gWSW(){delete pTexture;}   

   gTexture*    pTexture;
   };

class gTexture 
   {
   public:
       gTexture() {}
      ~gTexture();

//... a pointer to char[] here but will be also deleted in its destructor
   };

The last call before crashing is in ~gWSW(). Commenting "delete pTexture" out makes the program exit fine without errors or crashes. Before I continue and leaving it commented, I like to understand what the problem is please.

Ohh I believe I found the answer. It had been a while since I visited the "stack". I need to make an own copy constructor and thus provide a deep copy of every object.

In this way memory is allocated from the heap to a new pointer. The value at the new memory location is assigned the values from the original object.

Special thanks to Hans Passant that advised me to find the error by always making the copy constructor private.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM