【发布时间】:2019-10-11 18:52:18
【问题描述】:
struct base
{
base(){}
~base() { cout << "base destructor" << endl; }
};
struct derived : public base
{
derived() : base() { vec.resize(200000000); }
~derived() { cout << "derived destructor" << endl; }
vector<int> vec;
};
int main()
{
base* ptr = new derived();
delete ptr;
while (true)
{
}
}
由于删除操作没有调用派生对象的析构函数导致上述代码泄漏。但是……
struct base
{
base() {}
~base() { cout << "base destructor" << endl; }
};
struct derived : public base
{
derived() : base() {}
~derived() { cout << "derived destructor" << endl; }
int arr[200000000];
};
int main()
{
base* ptr = new derived();
delete ptr;
while (true)
{
}
}
在第二种情况下,尽管只调用了基本析构函数,但内存不会泄漏。所以我假设如果我的所有成员都是自动变量,那么没有基本析构函数是安全的吗?当派生对象的析构函数未被调用时,派生类中的“arr”成员是否永远不会超出范围?幕后发生了什么?
【问题讨论】:
-
这不是关于泄漏,而是关于未定义的行为。泄漏可能是 UB 的结果,但主要问题是它可能会做任何事情......
-
所以我假设如果我的所有成员都是自动变量,那么没有基析构函数是安全的? -- 如果你的“安全”派生类有
std::string是会员吗?或者,如果派生类有任何类型的成员,该成员的析构函数需要执行某种类型的“工作”,即关闭句柄,该怎么办?