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

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

    Try avoiding using pointers. They are last resort elements.

    class N {
    public:
        ~N() {
            std::cout << "Destroying object of type N";
        }
    };
    
    class M {
    public:
        M() {
           // n = new N; no need, default constructor by default
        }
    //  ~M() { //this should happen by default
    //      delete n;
    //  }
    private:
        N n; // No pointer here
    };
    

    Then use it this way

    main(int, char**)
    {
        M m;
    }
    

    This will display Destroying object of type N

提交回复
热议问题