how much does the default destructor do

后端 未结 5 2134
死守一世寂寞
死守一世寂寞 2021-02-14 04:11

Does the default destructor in C++ classes automatically delete members that are not explicitly allocated in code? For example:

class C {
  public:
    C() {}
           


        
5条回答
  •  情话喂你
    2021-02-14 05:03

    If your class/struct contains a pointer, and you explicitly allocate something for that pointer to refer to, then you normally need to write a matching delete in the dtor. Members that are directly embedded into the class/struct will be created and destroyed automatically.

    class X { 
        int x; 
        int *y;
    public:
        X() : y(new int) {}
        ~X() : { delete y; }    
    };
    

    Here X::x will be created/destroyed automatically. X::y (or, to be technically correct, what X::y points at) will not -- we allocate it in the ctor and destroy it in the dtor.

提交回复
热议问题