我看到在c++中有多种方法来分配和释放数据,我明白,当你调用malloc时你应该叫自由,当你使用新的操作符应与删除和对它是错误的把两个调用free()(例如,创建新的操作符),但是我不清楚我应该使用malloc / free,当我在现实世界中应该使用新的/删除程序。
如果你是c++专家,请告诉我你在这方面遵循的任何经验法则或惯例。
我看到在c++中有多种方法来分配和释放数据,我明白,当你调用malloc时你应该叫自由,当你使用新的操作符应与删除和对它是错误的把两个调用free()(例如,创建新的操作符),但是我不清楚我应该使用malloc / free,当我在现实世界中应该使用新的/删除程序。
如果你是c++专家,请告诉我你在这方面遵循的任何经验法则或惯例。
当前回答
只使用malloc和free来分配将由以c为中心的库和api管理的内存。对你控制的所有东西使用new和delete(以及[]变量)。
其他回答
如果你正在使用c++,尝试使用new/delete而不是malloc/calloc,因为它们是操作符。对于malloc/calloc,需要包含另一个头文件。不要在同一代码中混合使用两种不同的语言。它们的工作在各个方面都是相似的,都是从哈希表的堆段动态分配内存。
new和delete操作符可以操作类和结构,而malloc和free只适用于需要强制转换的内存块。
使用new/delete将有助于改进代码,因为您不需要将已分配的内存强制转换为所需的数据结构。
New将初始化结构的默认值,并正确地将结构中的引用链接到结构本身。
E.g.
struct test_s {
int some_strange_name = 1;
int &easy = some_strange_name;
}
因此,new struct test_s将返回一个带有工作引用的初始化结构,而malloc'ed版本没有默认值,实习引用也没有初始化。
来自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和new之间的区别。区别很简单:
malloc分配内存,而new分配内存并调用要分配内存的对象的构造函数。
因此,除非仅限于使用C,否则永远不要使用malloc,特别是在处理c++对象时。这将会破坏你的程序。
free和delete的区别也是一样的。不同之处在于,delete除了释放内存外,还会调用对象的析构函数。