I am transitioning from C to C++. In C++, is there any use for the malloc function, or can I just use the new keyword? For example:
class Node {
/* ... */
};
/* ... */
Node *node = malloc(sizeof(Node));
// vs
Node *node = new Node;
Which one should I use?
Use
new. You shouldn’t need to usemallocin 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 ofNode(if any exists) would not be called, and a subsequentdelete 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:
Note that for the latter examples (using
std::vectororstd::unique_ptr), there is no need todeletethe object; its memory will automatically be freed when it goes out of scope. You should strive to avoid bothnewandmallocin C++ programs, instead using objects that automatically manage their own memory.Here are your options and their benefits:
std::array<char, N>new char[N]std::unique_ptr<char[]>std::vector<char>