通过阅读我的旧 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/