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

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

    Imagine something like this:

    class M {
    public:
        M() { }
    //  ~M() {        // If this happens by default
    //      delete n; // then this will delete an arbitrary pointer!
    //  }
    private:
        N* n;
    };
    

    You're on your own with pointers in C++. No one will automatically delete them for you.

    The default destructor will indeed destroy all member objects. But the member object in this case is a pointer itself, not the thing it points to. This might have confused you.

    However, if instead of a simple built-in pointer, you will use a smart pointer, the destruction of such a "pointer" (which is actually a class) might trigger the destruction of the object pointed to.

提交回复
热议问题