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

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


当前回答

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

E.g.

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

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

其他回答

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

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

来自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而不是new/delete的情况是,当你使用realloc进行分配和重新分配(简单的pod类型,而不是对象)时,因为在c++中没有类似于realloc的函数(尽管这可以使用更c++的方法来完成)。

在c++中总是使用new。如果你需要一个无类型的内存块,你可以直接使用operator new:

void *p = operator new(size);
   ...
operator delete(p);

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