我应该删除 main.cpp 中由 new 关键字创建的东西吗?

Should I delete things created by the new keyword in main.cpp?

如果我理解正确(我并没有声称我理解),您应该 delete 在您的 Destructor 中使用 new 关键字创建的任何特定内容 class.这样可以防止内存泄漏。示例:

#include "Bar.h"

Bar *bar_ = NULL;

Foo::Foo()
{
    bar_= new Bar;
}

Foo::~Foo()
{
    delete bar_;
    bar_ = NULL;
}

但是你应该 delete newmain.cpp 中创建的东西吗?或者它们会在超出范围时被 Destructors 自动删除吗?

#include "Foo.h"

int main()
{
    MakeNewFoo();
    //Do other stuff and forget foo ever existed
    exit(0);
}

void MakeNewFoo(){        
    Foo *foo = new Foo;
}

您使用 new 创建的所有内容都将在程序的整个执行过程中存在于内存中,或者在使用 delete 删除时存在。所以是的,您应该在退出 MakeNewFoo.

之前删除 Foo

简短回答:是的,清理你的记忆。

更长的答案:

我不知道哪个 OS 不会 清除您造成的内存泄漏,但无论如何您都应该这样做。当您是 运行 内存泄漏检测工具并且不会被来自 main.cpp.

的一堆 "false" 积极因素所淹没时,它会变得特别有用

另外,这样的事情呢?

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_ptrstd::shared_ptr这样的智能指针,它会在什么时候为你释放内存他们超出了范围。

" Or will they just be automatically deleted by their Destructors when they go out of scope?"

不,它们不会被删除,你会遇到内存泄漏。

通常你不会在 C++ 中直接使用 new/delete。您宁愿使用标准 Dynamic memory management 类:

中的智能指针
class Foo {
    unique_ptr<Bar> bar_;

public:
    Foo() : bar_(new Bar) {}
    ~Foo() {} // delete is automatically managed by unique_ptr<Bar>
};

同样适用于您的免费函数示例:

void MakeNewFoo(){        
    std::unique_ptr<Foo> foo(new Foo());
    // Do stuff with foo
} // Will be deleted as soon foo goes out of scope

但是,如果您使用 new/new[],您总是必须使用 delete/delete[] 进行清理,是的。

首先,您显示的代码将无法编译,因为 new returns 一个指针,但是您的 foobar_ 变量未声明为指针,所以你需要解决这个问题:

#include "Bar.h"

Bar *bar_ = NULL;

Foo::Foo()
{
    bar_= new Bar;
}

Foo::~Foo()
{
    delete bar_;
    bar_ = NULL;
}

#include "Foo.h"

int main()
{
    MakeNewFoo();
    //Do other stuff and forget foo ever existed
    exit(0);
}

void MakeNewFoo(){        
    Foo *foo = new Foo;
}

现在,话虽如此,您可以看到 MakeNewFoo() 存在内存泄漏,因为使用 new 分配的 Foo 对象永远不会使用 delete 释放.是的,从技术上讲,OS 将在进程终止时回收内存。但是,如果 MakeNewFoo()main() 之外的代码其他地方被调用怎么办?因此,无论您 new 始终 delete 是一个好习惯(或者让 C++ 通过 std::auto_ptrstd::unique_ptrstd::shared_ptr 智能包装器为您完成类)。