我看到在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.

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

其他回答

如果你有C代码,你想移植到c++,你可能会留下任何malloc()调用。对于任何新的c++代码,我建议使用new。

有几件事是new做的,malloc没有:

New通过调用该对象的构造函数来构造该对象 New不需要对已分配的内存进行类型转换。 它不需要分配大量的内存,而是需要大量的内存 要构造的对象。

因此,如果使用malloc,则需要显式地执行上述操作,这并不总是实际的。此外,new可以重载,但malloc不能。

从较低的角度来看,new将在提供内存之前初始化所有内存,而malloc将保留内存的原始内容。

new和delete操作符可以操作类和结构,而malloc和free只适用于需要强制转换的内存块。

使用new/delete将有助于改进代码,因为您不需要将已分配的内存强制转换为所需的数据结构。

New vs malloc()

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

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

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

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

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