Why doesn't the C++ default destructor destroy

2019-03-12 06:12发布

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 {
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;
};

Then this should print the given message, but it doesn't:

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

13条回答
爷、活的狠高调
2楼-- · 2019-03-12 07:05

It is incorrect to say that the destructor deletes members. It invokes the destructor of each member (and base class), which for built-in types (like pointers) means doing nothing.

Matching news with deletes is your responsibility (either manually, or with the help of smart pointers).

查看更多
登录 后发表回答