Why doesn't the C++ default destructor destroy my objects?

前端 未结 13 2106
刺人心
刺人心 2020-12-14 06:59

The C++ specification says the default destructor deletes all non-static members. Nevertheless, I can\'t manage to achieve that.

I have this:

class N         


        
13条回答
  •  一整个雨季
    2020-12-14 07:29

    What makes you think the object n points to should be deleted by default? The default destructor destroys the pointer, not what it's pointing to.

    Edit: I'll see if I can make this a little more clear.

    If you had a local pointer, and it went out of scope, would you expect the object it points to to be destroyed?

    {
        Thing* t = new Thing;
    
        // do some stuff here
    
        // no "delete t;"
    }
    

    The t pointer is cleaned up, but the Thing it points to is not. This is a leak. Essentially the same thing is happening in your class.

提交回复
热议问题