如果我理解正确(我并没有声称我理解正确),您应该删除
在您的析构函数
中使用new
关键字创建的任何内容对于特定的类。这样可以防止内存泄漏。示例:
#include "Bar.h"
Bar *bar_ = NULL;
Foo::Foo()
{
bar_= new Bar;
}
Foo::~Foo()
{
delete bar_;
bar_ = NULL;
}
但是您应该删除
新
在main.cpp
中创建的东西吗?或者当它们超出范围时,它们会被它们的 Destructors
自动删除吗?
#include "Foo.h"
int main()
{
MakeNewFoo();
//Do other stuff and forget foo ever existed
exit(0);
}
void MakeNewFoo(){
Foo *foo = new Foo;
}
最佳答案
简短回答:是的,清理你的内存。
更长的答案:
我不知道哪个操作系统不会清除您造成的内存泄漏,但无论如何您都应该这样做。当您运行内存泄漏检测工具并且不会被来自 main.cpp 的一堆“误报”所淹没时,它会变得特别有用。
此外,像这样的事情呢?
int main()
{
BigStructure foo* = new BigStructure(/*...*/);
// some computations to get variables
// at this point foo is no longer needed
RestOfProgramFunction1(); // long running, resource heavy
RestOfProgramFunction2(); // long running, resource heavy
}
现在您已经占用了一堆不再需要的内存,这为您需要的其他功能留下了更少的内存。
您有责任释放您分配的任何内存。如果你不想关心什么时候做它,使用像std::unique_ptr
或std::shared_ptr
这样的智能指针,当它们超出范围时,这将为您释放内存。
关于c++ - 我应该删除 main.cpp 中 new 关键字创建的东西吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28800798/