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

前端 未结 13 2145
刺人心
刺人心 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:44

    class N {
    public:
        ~N() {
            std::cout << "Destroying object of type N";
        }
    };
    
    class M {
    public:
        M() {
            n = new N;
        }
    //  ~M() { //this should happen by default
    //      delete n;
    //  }
    private:
        N* n;
    };
    

    and now the expectation is :

    M* m = new M();
    delete m; //this should invoke the default destructor
    

    It will only happen, if the class M is derived from N:

    class M: Class N {
    ...
    

    Only in this situation,

    M* m = new M()
    

    will call constructor of N and then constructor of M, where as

    delete m;
    

    will automatically call destructor of M first and then N

提交回复
热议问题