Malloc函数在C ++中 [英] Malloc function in C++
问题描述
我从C过渡到C ++。在C ++中,malloc函数有什么用处吗?或者我可以使用new关键字声明它。例如:
class Node
{
...
}
...
Node * node1 = malloc(sizeof(Node)); // malloc
Node * node2 = new Node; // new
我应该使用哪一个?
使用 new
。你不应该在C ++程序中使用 malloc
,除非它与某些C代码交互,或者你有某种原因以特殊方式管理内存。
您的 node = malloc(sizeof(Node))
的示例是一个坏主意,因为 Node
(如果存在)不会被调用,并且后续的删除节点
将具有未定义的结果。
如果你需要一个字节缓冲区,而不是一个对象,你通常会这样做:
char * buffer = new char [1024];
或者,最好是这样:
std :: vector< char>缓冲器(1024);
请注意,对于第二个示例(使用 std :: vector<
),不需要 delete
对象;它的内存将在超出范围时自动释放。你应该努力避免在C ++程序中使用 new
和 malloc
,而是使用自动管理自己内存的对象。 / p>
I am transitioning to C++ from C. In C++, is there any use for the malloc function? Or can I just declare it with the "new" keyword. For example:
class Node
{
...
}
...
Node *node1 = malloc(sizeof(Node)); //malloc
Node *node2 = new Node; //new
Which one should I use?
Use 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.
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;
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; 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.
这篇关于Malloc函数在C ++中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!