Malloc 与 C++ 中的 new

发布于 2024-08-30 10:19:46 字数 278 浏览 5 评论 0原文

我正在从 C 过渡到 C++。在 C++ 中,malloc 函数有什么用处,或者我可以只使用 new 关键字吗?例如:

class Node {
    /* ... */
};

/* ... */

Node *node = malloc(sizeof(Node));
// vs
Node *node = new Node;

我应该使用哪一个?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

欢烬 2024-09-06 10:19:46

使用new。您不需要在 C++ 程序中使用 malloc,除非它与某些 C 代码交互或者您有某种原因以特殊方式管理内存。

您的 node = malloc(sizeof(Node)) 示例是一个坏主意,因为 Node 的构造函数(如果存在)不会被调用,并且后续的 < code>delete node; 将产生未定义的结果。

如果您需要一个字节缓冲区,而不是一个对象,您通常会想要执行以下操作:

char *buffer = new char[1024];
// or preferably:
std::unique_ptr<char[]> buffer = std::make_unique<char[]>(1024);
// or alternatively:
std::vector<char> buffer(1024);

请注意,对于后面的示例(使用 std::vectorstd::unique_ptr),无需删除该对象;当它超出范围时,它的内存将自动释放。您应该努力避免在 C++ 程序中同时使用 newmalloc,而是使用自动管理其自身内存的对象。

以下是您的选项及其优点:

方法动态调整大小自动管理可调整大小
std:: array
new char[N]
std ::unique_ptr
std::vector

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:
std::unique_ptr<char[]> buffer = std::make_unique<char[]>(1024);
// or alternatively:
std::vector<char> buffer(1024);

Note that for the latter examples (using std::vector or std::unique_ptr), 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.

Here are your options and their benefits:

MethodDynamically SizedAutomatically ManagedResizable
std::array<char, N>NoYesNo
new char[N]YesNoNo
std::unique_ptr<char[]>YesYesNo
std::vector<char>YesYesYes
秋风の叶未落 2024-09-06 10:19:46

C++ 中 malloc() 的直接等价物是 operator new(),它也分配原始内存,但在大多数情况下,new 表达式就是你想要的。 new 表达式既分配适当数量的原始内存,又初始化该内存位置中的对象,返回指向新对象的正确类型的指针。

在您的情况下,new Node 是正确的,因为它分配内存并初始化一个新的Node 对象。简单地调用 malloc 并将结果转换为指向 Node 的指针将无法正确构造 Node 对象。如果 Node 不是 POD 结构(例如,当它或其子对象之一具有应调用的构造函数时),这一点至关重要。

您应该避免在不需要的地方进行动态分配;在需要的地方,通常最好使用动态分配的对象的地址初始化某种智能指针,这样就不可能“忘记”删除该对象。

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.

还不是爱你 2024-09-06 10:19:46

newmalloc 之间的主要区别之一是 new 将调用对象的构造函数。

另一个区别是,如果内存无法成功分配,new 将引发异常(可能会被编译器pragma 规避)。 malloc可能会导致生成系统信号。尽管一些C++库通过调用malloc来实现new

在某些情况下,可能需要动态分配对象而不调用其构造函数。 20 多年来,我还没有遇到过任何问题(甚至在嵌入式系统领域也没有遇到过)。

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

音盲 2024-09-06 10:19:46

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

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.

月野兔 2024-09-06 10:19:46

我的习惯是对原始类型和 C 兼容结构使用 malloc() ,对其他所有内容使用 new

在过去,这提供了与 C 库代码更好的互操作性。在 Linux 上,这仍然是正确的。在 Windows 上,您需要保持分配它的库释放它的习惯。

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

In the old days this gave better interop with C library code. On Linux, this is still true. On Windows, you need to keep the habit of the library that allocates it frees it.

深海不蓝 2024-09-06 10:19:46

必须使用malloc 的关键情况是原始代码是否调用realloc。当然,您可以重新实现所需的所有内容,但这样做并没有多大好处。

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.

沧桑㈠ 2024-09-06 10:19:46

一般来说,除非与 C 代码交互,否则请使用 new

关键点在于,使用 new 分配的内容必须使用 delete 释放,使用 malloc 分配的内容必须使用 delete 释放。代码>免费。您不能使用 new 进行分配,也不能使用 free() 进行释放,反之亦然。因此,大约唯一需要 malloc 的时间是当您需要将数据传递给某些可能 free()realloc() 的 C 代码时> 它。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文