当使用std::list<std::string>时,我偶然发现了堆栈溢出问题std::string的内存泄漏,其中一个注释说:

不要用那么多new。我看不出你为什么在任何地方都用新的。你可以在c++中通过值创建对象,这是使用该语言的一个巨大优势。您不必分配堆上的所有内容。不要像Java程序员那样思考。

我不太确定他这么说是什么意思。

为什么在c++中应该尽可能多地根据值创建对象,这在内部有什么不同?我误解了答案吗?


当前回答

Pre-C + + 17:

因为即使您将结果包装在智能指针中,它也容易发生细微的泄漏。

考虑一个“小心”的用户,他记得在智能指针中包装对象:

foo(shared_ptr<T1>(new T1()), shared_ptr<T2>(new T2()));

这段代码很危险,因为不能保证在T1或T2之前构造shared_ptr。因此,如果新T1()或新T2()中的一个在另一个成功后失败,那么第一个对象将被泄露,因为不存在shared_ptr来销毁和释放它。

解决方法:使用make_shared。

Post-C + + 17:

这不再是一个问题:c++ 17对这些操作的顺序施加了约束,在这种情况下,确保每次调用new()必须立即构造相应的智能指针,中间没有其他操作。这意味着,在调用第二个new()时,可以保证第一个对象已经被包装在其智能指针中,从而防止在抛出异常时发生任何泄漏。

Barry在另一个回答中提供了关于c++ 17引入的新求值顺序的更详细的解释。

感谢@Remy Lebeau指出这在c++ 17中仍然是一个问题(尽管不是那么严重):shared_ptr构造函数可能无法分配它的控制块和抛出,在这种情况下,传递给它的指针不会被删除。

解决方法:使用make_shared。

其他回答

两个原因:

在这种情况下没有必要。您正在使代码不必要地变得更加复杂。 它在堆上分配空间,这意味着您必须记住稍后删除它,否则将导致内存泄漏。

C++ doesn't employ any memory manager by its own. Other languages like C# and Java have a garbage collector to handle the memory C++ implementations typically use operating system routines to allocate the memory and too much new/delete could fragment the available memory With any application, if the memory is frequently being used it's advisable to preallocate it and release when not required. Improper memory management could lead memory leaks and it's really hard to track. So using stack objects within the scope of function is a proven technique The downside of using stack objects are, it creates multiple copies of objects on returning, passing to functions, etc. However, smart compilers are well aware of these situations and they've been optimized well for performance It's really tedious in C++ if the memory being allocated and released in two different places. The responsibility for release is always a question and mostly we rely on some commonly accessible pointers, stack objects (maximum possible) and techniques like auto_ptr (RAII objects) The best thing is that, you've control over the memory and the worst thing is that you will not have any control over the memory if we employ an improper memory management for the application. The crashes caused due to memory corruptions are the nastiest and hard to trace.

因为堆栈速度更快,而且防漏

在c++中,只需要一条指令就可以为给定函数中的每个局部作用域对象在堆栈上分配空间,而且不可能泄漏任何内存。该评论意图(或应该意图)说“使用堆栈而不是堆”之类的话。

Pre-C + + 17:

因为即使您将结果包装在智能指针中,它也容易发生细微的泄漏。

考虑一个“小心”的用户,他记得在智能指针中包装对象:

foo(shared_ptr<T1>(new T1()), shared_ptr<T2>(new T2()));

这段代码很危险,因为不能保证在T1或T2之前构造shared_ptr。因此,如果新T1()或新T2()中的一个在另一个成功后失败,那么第一个对象将被泄露,因为不存在shared_ptr来销毁和释放它。

解决方法:使用make_shared。

Post-C + + 17:

这不再是一个问题:c++ 17对这些操作的顺序施加了约束,在这种情况下,确保每次调用new()必须立即构造相应的智能指针,中间没有其他操作。这意味着,在调用第二个new()时,可以保证第一个对象已经被包装在其智能指针中,从而防止在抛出异常时发生任何泄漏。

Barry在另一个回答中提供了关于c++ 17引入的新求值顺序的更详细的解释。

感谢@Remy Lebeau指出这在c++ 17中仍然是一个问题(尽管不是那么严重):shared_ptr构造函数可能无法分配它的控制块和抛出,在这种情况下,传递给它的指针不会被删除。

解决方法:使用make_shared。

New在堆上分配对象。否则,对象分配在堆栈上。查一下两者的区别。