c++ - 是 Foo* f = new Foo 好的 C++ 代码吗

标签 c++ memory-management memory-leaks

通过阅读我的旧 C++ 日志,我发现了一些东西。

其中一篇文章断言

Foo *f = new Foo();

基本上是几乎不能接受的专业 C++ 代码,自动内存管理解决方案是合适的。

是这样吗?

编辑:改写:对于新的 C++ 代码,直接内存管理是否 Not Acceptable ,一般大多数新代码是否应该使用 auto_ptr(或其他管理包装器)?

最佳答案

这个例子很像Java。
在 C++ 中,我们仅在需要时才使用动态内存管理。
更好的选择是声明一个局部变量。

{
    Foo    f;

    // use f

} // f goes out of scope and is immediately destroyed here.

如果您必须使用动态内存,请使用智能指针。

// In C++14
{
    std::unique_ptr<Foo>  f = std::make_unique<Foo>(); // no need for new anymore
}

// In C++11
{
    std::unique_ptr<Foo>  f(new Foo);  // See Description below.
}

// In C++03
{
    std::auto_ptr<Foo>    f(new Foo);  // the smart pointer f owns the pointer.
                                       // At some point f may give up ownership to another
                                       // object. If not then f will automatically delete
                                       // the pointer when it goes out of scope..

}

提供了一大堆 os 智能指针 int std::和 boost::(现在有些在 std::tr1 中)选择合适的并使用它来管理对象的生命周期。

Smart Pointers: Or who owns you baby?

从技术上讲,您可以使用 new/delete 来进行内存管理。
但在真正的 C++ 代码中,它几乎从未完成。几乎总是有比手动进行内存管理更好的选择。

一个简单的例子是 std::vector。在幕后,它使用 new 和 delete。但你永远无法从外面分辨出来。这对类的用户是完全透明的。用户所知道的是, vector 将取得对象的所有权,并且当 vector 被销毁时,它将被销毁。

关于c++ - 是 Foo* f = new Foo 好的 C++ 代码吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2040210/

相关文章:

c - 使用 DnsGetCacheDataTable 时内存泄漏

c++ - 使用 symstore.exe 无法在 Windbg 或 Visual Studio 中为小型转储加载符号

c++ - 指向所有者类的指针

c++ - 函数内部的变量与 C++ 中作为参数的变量之间的区别

c++ - Visual Studio 如何处理已删除的指针,为什么?

linux - 如何在Linux上的matlab中检查最大的连续空闲 block ?

ios - UISplitViewController 在 iOS 9 中是否存在保留周期错误?

python - Pandas.groupby.apply() 内存泄漏?

c++ - 在模板中访问函数模板参数的结果类型?

c - 为链表数组分配内存