Practical application of class destructor

后端 未结 6 1553
孤街浪徒
孤街浪徒 2021-01-06 09:48

I\'m currently trying to learn about classes and constructors/destructors. I understand what the two do, but I\'m having a harder time with the destructors because I can\'t

6条回答
  •  南方客
    南方客 (楼主)
    2021-01-06 10:21

    Extending @Als's answer here, for example you have a class,

    class A {
        B* ptrB; // B is another class / struct / internal type
        A() { ptrB = new B(); }
    }
    
    int main() {
        A* ptrA = new A();
        // Do something with A
        delete ptrA; // This does not free ptrA->ptrB
    }
    

    To take care of this problem, declare a destructor in A as follows,

    ~A() { delete ptrB; } // This is called every time delete is called on
                          // an object of A
    

提交回复
热议问题