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

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


当前回答

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

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

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

其他回答

来自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.

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

New将初始化结构的默认值,并正确地将结构中的引用链接到结构本身。

E.g.

struct test_s {
    int some_strange_name = 1;
    int &easy = some_strange_name;
}

因此,new struct test_s将返回一个带有工作引用的初始化结构,而malloc'ed版本没有默认值,实习引用也没有初始化。

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

New vs malloc()

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

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

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

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

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

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