在析构函数中调用"delete"运算符时"compiler is out of heap space"编译器错误

Compiler error "compiler is out of heap space" when calling `delete` operator in the destructor

本文关键字:heap out of space 错误 编译器 is 析构函数 调用 delete 运算符      更新时间:2023-10-16

我写了一个名为">TreeContainer"的类。我的目标是设计一个树容器,将内容保存在树状层次结构中。每个树容器都应该像文件系统中的文件夹/目录一样工作。文件夹(树(可以具有子文件夹(子树(和其他文件(子项(。

我把它包含在另一个源文件中,说它的名字是">TreeUser.cpp"。当我尝试调试/运行我的项目时,Visual Studio 会逐个编译项目源文件,并在 IDE 的"输出"面板中看到当前正在编译的文件。当涉及到TreeUser.cpp文件时,它需要太多时间。它最终给出了下面的致命错误,编译停止了。

错误 C1060 编译器堆空间
不足[此处的项目名称]
[此处的 VisualStudio 安装路径]\Visual Studio\vc\tools\msvc\14.14.26428\include\xmemory0 962

该类的代码如下。

树容器.cpp

#pragma once
#include <vector>
template <class T>
class TreeContainer
{
public:
using SubTreeContainerType = std::vector<TreeContainer<T *> *>;
using SubItemContainerType = std::vector<T *>;
TreeContainer();
~TreeContainer();
// ... (Lots of member functions here. Removing or keeping them has no effect.)
private:
SubTreeContainerType SubTrees;
SubItemContainerType SubItems;
};
template <class T>
TreeContainer<T>::TreeContainer()
: SubTrees(), SubItems()
{
}
template <class T>
TreeContainer<T>::~TreeContainer()
{
for (typename SubTreeContainerType::iterator it=SubTrees.begin(); it!=SubTrees.end(); ++it)
{
//delete *it; (I get the error when I uncomment this line.)
}
for (typename SubItemContainerType::iterator it=SubItems.begin(); it!=SubItems.end(); ++it)
{
delete *it;
}
}

经过多次试验,我发现析构函数中的行导致了问题。删除它会消除问题。但是我需要那行来清理内存。

在该行中,我正在调用容器SubTrees内容的delete运算符。它应该递归调用每个子树上的析构函数。我在这里做错了什么,还是这是Visual Studio中的一个错误。

IDE 版本:Visual Studio Community 2017 15.7.4

命令行选项:

/permissive-/GS/W3/wd"4290"/wd"5040"/Zc:wchar_t/ZI/Gm-/Od/sdl/fd"x64\Debug\vc141.pdb"/Zc:inline/fp:precise/d "SC_DEBUG"/D "_SILENCE_CXX17_CODECVT_HEADER_DEPRECATION_WARNING"/D "_UNICODE"/

D "UNICODE"/errorReport:prompt/WX-/Zc:forScope/RTC1/Gd/MDd/std:c++17/FC/Fa"x64\Debug\"/EHsc/nologo/Fo"x64\Debug\"/fp"x64\Debug\Project Name.pch"/diagnostics:经典

看起来您从模板创建了无限多个类,因为SubTreeContainerTypeTreeContainer<T>引用TreeContainer<T *>(T指针的容器(。

而析构函数需要子树向量的析构函数,子树向量又需要TreeContainer<T *>的析构函数,而子树的析构函数需要TreeContainer<T **>等pp的析构函数。

溶液:

using SubTreeContainerType = std::vector<TreeContainer<T> *>;

或者,如果您确实希望子树容器引用指向T的指针,请在实现方法之前为中断递归的指针添加模板专用化。