简体   繁体   English

C ++中的Malloc函数

[英]Malloc function in C++

I am transitioning to C++ from C. In C++, is there any use for the malloc function? 我正在从C转换到C ++。在C ++中,malloc函数有用吗? Or can I just declare it with the "new" keyword. 或者我可以使用“new”关键字声明它。 For example: 例如:

class Node
{
    ...
}
...
Node *node1 = malloc(sizeof(Node));        //malloc
Node *node2 = new Node;                    //new

Which one should I use? 我应该使用哪一个?

Use new . 使用new You shouldn't need to use malloc in a C++ program, unless it is interacting with some C code or you have some reason to manage memory in a special way. 您不应该在C ++程序中使用malloc ,除非它与某些C代码交互,或者您有某种理由以特殊方式管理内存。

Your example of node = malloc(sizeof(Node)) is a bad idea, because the constructor of Node (if any exists) would not be called, and a subsequent delete node; 你的node = malloc(sizeof(Node))例子是个坏主意,因为不会调用Node的构造函数(如果存在),以及后续的delete node; would have undefined results. 会有不确定的结果。

If you need a buffer of bytes, rather than an object, you'll generally want to do something like this: 如果你需要一个字节缓冲区而不是一个对象,你通常会想要做这样的事情:

char *buffer = new char[1024];

or, preferably, something like this: 或者,最好是这样的事情:

std::vector<char> buffer(1024);

Note that for the second example (using std::vector<> ), there is no need to delete the object; 注意,对于第二个例子(使用std::vector<> ),不需要delete对象; its memory will automatically be freed when it goes out of scope. 当它超出范围时,它的内存将自动释放。 You should strive to avoid both new and malloc in C++ programs, instead using objects that automatically manage their own memory. 您应该努力避免在C ++程序中使用newmalloc ,而是使用自动管理自己内存的对象。

The direct equivalent of malloc() in C++ is operator new() which also allocates raw memory, however in most cases a new expression is what you want. 在C ++中直接等效的malloc()operator new() ,它也分配原始内存,但在大多数情况下, new表达式就是你想要的。 A new expression both allocates an appropriate amount of raw memory and initializes an object in that memory location, returning a correctly typed pointer to the new object. new表达式既分配适当数量的原始内存,又初始化该内存位置中的对象,返回正确键入的指向新对象的指针。

In your case , new Node is correct as it allocates memory and initializes a new Node object. 在您的情况下, new Node是正确的,因为它分配内存并初始化一个新的Node对象。 Simply calling malloc and casting result to a pointer to Node won't correctly construct the Node object. 简单地调用malloc并将结果转换为指向Node的指针将无法正确构造Node对象。 This is critical if Node is not a POD-struct (eg when it or one of its sub-objects has a constructor that should be called). 如果Node不是POD结构(例如,当它或它的一个子对象具有应该被调用的构造函数时),这是至关重要的。

You should avoid dynamic allocation where it is not needed; 你应该避免在不需要的地方进行动态分配; where it is needed, it is often best to initialize some sort of smart pointer with the address of the dynamically allocated object so that it's not possible to 'forget' to delete the obejct. 在需要的地方,通常最好使用动态分配的对象的地址初始化某种智能指针,这样就不可能“忘记” delete该对象。

One of the primary differences between new and malloc is that new will call the object's constructor. newmalloc之间的主要区别之一是new将调用对象的构造函数。

Another difference is that new will throw an exception (may be circumvented by a compiler pragma ) if the memory cannot be succesfully allocated. 另一个区别是,如果无法成功分配内存, new将抛出异常(可能被编译器编译pragma规避)。 The malloc may cause a system signal to be generated. malloc可以导致生成系统信号。 Although some C++ libraries implement new by calling malloc . 虽然一些C ++库通过调用malloc实现new

There may be a few instances where objects need to be dynamically allocated without invoking their constructors. 可能有一些实例需要动态分配对象而不调用其构造函数。 In over 20 years, I haven't come across any (not even in the embedded systems arena). 20多年来,我没有遇到任何问题(甚至在嵌入式系统领域也没有)。

好吧,我能想到的一件事,如果你使用新的,如果你最终需要它,你将会错过realloc。

They key situation in which you must use malloc is if the original code ever calls realloc . 它们必须使用malloc关键情况是原始代码是否调用realloc Of course you can reimplement everything needed, but there isn't that much advantage in doing so. 当然,您可以重新实现所需的一切,但这样做并没有那么多优势。

我的习惯是将malloc()用于原始类型和C兼容结构,并将其用于其他所有结构。

In general, use new except when interfacing with C code. 通常,除了与C代码接口外,使用new

The key point on this is that what is allocated with new must be freed with delete , and what is allocated with malloc must be freed with free . 关键是要用new分配的内容必须通过delete释放,而malloc分配的内容必须free释放。 You cannot allocate with new and free with free() or vice-versa. 您无法使用free()分配new和free,反之亦然。 So, about the only time you need malloc is when you need to pass data off to some C code that might free() or realloc() it. 所以,关于你需要malloc的唯一时间是你需要将数据传递给一些可能free()realloc() C代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM