Parent 持有指向 child 数据成员的指针并在析构函数中使用数据成员函数

Parent hold pointer to child data member and used the data member function in destructor

我相信我发现了现有代码的错误,但它确实有效。能否帮忙验证一下我的理解是否正确?

它是关于一个 parent class 持有一个指向它的 child class 数据 object 的 object 指针。在它的(parent)析构函数中,它使用 object 指针进行函数访问。我相信当调用 parent 析构函数时,child 已经被析构,因此 parent 指针指向的 object 不再有效。我在下面举个例子:

我对下面代码的问题是 parent 析构函数是否正确?

#include <iostream>
#include <string>
using namespace std;

class object {
public:

    object(string na):name(na){}

    string get_name(){
        return name;
    }

private:
    string name;
};

class parent {

public:

    ~parent(){
        cout<<"hello"<<endl;
        cout<<mp->get_name();  **//!!!! (is this correct use mp here?)**
    }
protected:
    object* mp;

};


class child:public parent {

public:

    child():m("hello"){
        parent::mp=&m;
    }


private:
    object m;
};

int main()
{

 child a;

 return 0;
}

I belive when the parent destructor is called, the child has already been destructed

§ 12.4.8 将成为我最喜欢的标准报价。

After executing the body of the destructor and destroying any automatic objects allocated within the body, a destructor for class X calls the destructors for X's direct non-variant non-static data members(...)

成员的析构函数在class dtor 的主体之后执行,因此调用成员的成员函数是安全的。

据说...

在你的例子中,虽然 mp 是完全有效的,但它指向的值不是。由于 parent 析构函数在 child 析构函数之后运行,因此所有者的子项的值也被销毁,从而使父项具有悬空指针。

不正确。

析构函数调用顺序:

  1. child 析构函数
  2. object 析构函数(因为它是 child class 的成员)
  3. parent 析构函数

看看这个:parent 保留一个指向 object 的指针,它是 child class.

的成员
child():m("hello"){
    parent::mp=&m;
}

因此,当您尝试通过 parent 析构函数中的指针访问它时,object 已经被析构:

~parent(){
    cout<<"hello"<<endl;
    cout<<mp->get_name();  //!!!! this is incorrect
}