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

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

    The default destructor looks like this:

    ~M()
    {
    }
    

    The default destructor does not insert code to do anything with pointed-to things. What if you had n pointing to a stack variable? Automatically inserting a delete n would crash.

    The default destructor calls the destructor on each member of the class (member.~T()). For a pointer, that's a no-op (does nothing), just like myint.~int() does nothing, but for member classes with defined destructors, the destructor is called.

    Here's another example:

    struct MyClass {
    public:
        MyClass() { .. } // doesn't matter what this does
    
        int x;
        int* p;
        std::string s;
        std::vector v;
    };
    

    The default destructor in reality is doing this:

    MyClass::~MyClass()
    {
        // Call destructor on member variables in reverse order
        v.~std::vector(); // frees memory
        s.~std::string();      // frees memory
        p.~int*();             // does nothing, no custom destructor
        x.~int();              // does nothing, no custom destructor
    }
    

    Of course, if you define a destructor, the code in your destructor runs before the member variables are destroyed (obviously, otherwise they would not be valid!).

提交回复
热议问题