【发布时间】:2021-11-02 07:10:33
【问题描述】:
我写道:
class image {
public:
linked_list<int, int> UnLabeledList;
int *SegArray = nullptr;
int Total_Segments = 0;
explicit image(int Segments) : SegArray(new int[Segments]) {
Total_Segments = Segments;
for (int i = 0; i < Segments; ++i) {
if (!UnLabeledList.push_back(i, NOT_INIT)) { // allocation failed for one node (Doesn't throw any exception)
~UnLabeledList();
delete[] SegArray;
throw;
}
SegArray[i] = NOT_INIT;
}
};
};
万一分配失败,我想销毁对象(因为它以前分配过节点),例如在i==5 分配失败时。如何调用UnLabeledList的d'tor来防止内存泄漏?
【问题讨论】:
-
~UnLabeledList();是做什么的? -
你不用,保证会自动销毁。此外,如果您将
std::vector<int>用于SegArray,那么您也不必调用delete。 -
镜像销毁时会销毁
-
继续阅读你的 C++ 教程,它应该解释这些概念。如果您没有好的学习资源,请查看stackoverflow.com/questions/388242/…。另外,只是一个提示:我不记得曾经使用过
new[]。在您想要这样做的所有情况下,您可能应该改用std::vector<>。 -
UnLabeledList将在image被销毁时被销毁。如果你真的有内存泄漏,它们不是由于缺乏破坏造成的。
标签: c++ class destructor new-operator allocation