我看到在c++中有多种方法来分配和释放数据,我明白,当你调用malloc时你应该叫自由,当你使用新的操作符应与删除和对它是错误的把两个调用free()(例如,创建新的操作符),但是我不清楚我应该使用malloc / free,当我在现实世界中应该使用新的/删除程序。

如果你是c++专家,请告诉我你在这方面遵循的任何经验法则或惯例。


当前回答

来自c++ FQA Lite:

[16.4] Why should I use new instead of trustworthy old malloc()? FAQ: new/delete call the constructor/destructor; new is type safe, malloc is not; new can be overridden by a class. FQA: The virtues of new mentioned by the FAQ are not virtues, because constructors, destructors, and operator overloading are garbage (see what happens when you have no garbage collection?), and the type safety issue is really tiny here (normally you have to cast the void* returned by malloc to the right pointer type to assign it to a typed pointer variable, which may be annoying, but far from "unsafe"). Oh, and using trustworthy old malloc makes it possible to use the equally trustworthy & old realloc. Too bad we don't have a shiny new operator renew or something. Still, new is not bad enough to justify a deviation from the common style used throughout a language, even when the language is C++. In particular, classes with non-trivial constructors will misbehave in fatal ways if you simply malloc the objects. So why not use new throughout the code? People rarely overload operator new, so it probably won't get in your way too much. And if they do overload new, you can always ask them to stop.

对不起,我就是忍不住。:)

其他回答

如果你处理的数据不需要构造/销毁,需要重新分配(例如,一个大的整数数组),那么我相信malloc/free是一个很好的选择,因为它给你realloc,这比new-memcpy-delete快得多(它在我的Linux盒子上,但我猜这可能是平台相关的)。如果你使用的c++对象不是POD并且需要构造/销毁,那么你必须使用new和delete操作符。

无论如何,如果可以利用realloc可以给您的速度提升(如果您正在重新分配大型POD数组,有时是一个显著的提升),我不明白为什么不应该同时使用这两种方法(前提是您释放了错误的内存并删除了用new分配的对象)。

除非你需要它,否则你应该坚持在c++中使用new/delete。

除非被迫使用C,否则永远不要使用malloc。总是使用new。

如果你需要大量的数据,可以这样做:

char *pBuffer = new char[1024];

尽管这是不正确的,但要小心:

//This is incorrect - may delete only one element, may corrupt the heap, or worse...
delete pBuffer;

相反,你应该在删除数据数组时这样做:

//This deletes all items in the array
delete[] pBuffer;

new关键字是c++实现它的方式,它将确保你的类型的构造函数被调用。new关键字也更加类型安全,而malloc根本不是类型安全的。

我认为使用malloc有益的唯一方式是需要改变数据缓冲区的大小。new关键字没有类似realloc的方式。realloc函数可能能够更有效地扩展内存块的大小。

值得一提的是,你不能将new/free和malloc/delete混合使用。

注:本题部分答案无效。

int* p_scalar = new int(5);  // Does not create 5 elements, but initializes to 5
int* p_array  = new int[5];  // Creates 5 elements

很少考虑使用malloc/free而不是new/delete的情况是,当你使用realloc进行分配和重新分配(简单的pod类型,而不是对象)时,因为在c++中没有类似于realloc的函数(尽管这可以使用更c++的方法来完成)。

New vs malloc()

1) new是操作符,malloc()是函数。

2) new调用构造函数,而malloc()不调用。

3) new返回准确的数据类型,而malloc()返回void *。

4) new从不返回NULL(失败时会抛出),而malloc()返回NULL

5)重新分配内存不能由new处理,而malloc()可以

malloc()在C语言中用于动态分配内存 而在c++中,同样的工作由new()完成。 所以你不能混合两种语言的编码习惯。 如果你问calloc和malloc()之间的差异,那就好了