开发者

Malloc function in C++

开发者 https://www.devze.com 2022-12-28 21:23 出处:网络
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:

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.


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

In your case , new Node is correct as it allocates memory and initializes a new Node object. Simply calling malloc and casting result to a pointer to Node won't correctly construct the Node object. This is critical if Node is not a POD-struct (e.g. when it or one of its sub-objects has a constructor that should be called).

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.


One of the primary differences between new and malloc is that new will call the object's constructor.

Another difference is that new will throw an exception (may be circumvented by a compiler pragma) if the memory cannot be succesfully allocated. The malloc may cause a system signal to be generated. Although some C++ libraries implement new by calling malloc.

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).


Well, the one thing I can think of, if you're using new you're going to miss realloc if you end up needing it.


They key situation in which you must use malloc is if the original code ever calls realloc. Of course you can reimplement everything needed, but there isn't that much advantage in doing so.


My habit is to use malloc() for primitive types and C compatible structs, and new for everything else.


In general, use new except when interfacing with C code.

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. You cannot allocate with new and free with free() or vice-versa. 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号