【发布时间】:2016-01-17 13:25:52
【问题描述】:
我相信我发现了现有代码的错误,但它确实有效。您能帮忙验证一下我的理解是否正确吗?
它是关于一个父类持有一个指向其子类的数据对象的对象指针。在其(父)析构函数中,它使用对象指针进行函数访问。我相信当调用父析构函数时,孩子已经被析构了,所以父指针指向的对象不再有效。下面我举个例子:
我对下面代码的问题是父析构函数是否正确?
#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;
}
【问题讨论】:
-
难以捉摸的“它确实有效”是未定义行为的一个例子。
标签: c++ pointers constructor destructor