Malloc 与 C++ 中的 new
我正在从 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
使用
new
。您不需要在 C++ 程序中使用malloc
,除非它与某些 C 代码交互或者您有某种原因以特殊方式管理内存。您的
node = malloc(sizeof(Node))
示例是一个坏主意,因为Node
的构造函数(如果存在)不会被调用,并且后续的 < code>delete node; 将产生未定义的结果。如果您需要一个字节缓冲区,而不是一个对象,您通常会想要执行以下操作:
请注意,对于后面的示例(使用
std::vector
或std::unique_ptr
),无需删除
该对象;当它超出范围时,它的内存将自动释放。您应该努力避免在 C++ 程序中同时使用new
和malloc
,而是使用自动管理其自身内存的对象。以下是您的选项及其优点:
std:: array
new char[N]
std ::unique_ptr
std::vector
Use
new
. You shouldn't need to usemalloc
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 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::vector
orstd::unique_ptr
), there is no need todelete
the object; its memory will automatically be freed when it goes out of scope. You should strive to avoid bothnew
andmalloc
in 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>
C++ 中
malloc()
的直接等价物是operator new()
,它也分配原始内存,但在大多数情况下,new
表达式就是你想要的。 new 表达式既分配适当数量的原始内存,又初始化该内存位置中的对象,返回指向新对象的正确类型的指针。在您的情况下,
new Node
是正确的,因为它分配内存并初始化一个新的Node
对象。简单地调用malloc
并将结果转换为指向Node
的指针将无法正确构造Node
对象。如果 Node 不是 POD 结构(例如,当它或其子对象之一具有应调用的构造函数时),这一点至关重要。您应该避免在不需要的地方进行动态分配;在需要的地方,通常最好使用动态分配的对象的地址初始化某种智能指针,这样就不可能“忘记”
删除
该对象。The direct equivalent of
malloc()
in C++ isoperator new()
which also allocates raw memory, however in most cases anew
expression is what you want. Anew
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 newNode
object. Simply callingmalloc
and casting result to a pointer toNode
won't correctly construct theNode
object. This is critical ifNode
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.new
和malloc
之间的主要区别之一是new
将调用对象的构造函数。另一个区别是,如果内存无法成功分配,
new
将引发异常(可能会被编译器pragma
规避)。malloc
可能会导致生成系统信号。尽管一些C++库通过调用malloc
来实现new
。在某些情况下,可能需要动态分配对象而不调用其构造函数。 20 多年来,我还没有遇到过任何问题(甚至在嵌入式系统领域也没有遇到过)。
One of the primary differences between
new
andmalloc
is thatnew
will call the object's constructor.Another difference is that
new
will throw an exception (may be circumvented by a compilerpragma
) if the memory cannot be succesfully allocated. Themalloc
may cause a system signal to be generated. Although some C++ libraries implementnew
by callingmalloc
.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).
好吧,我能想到的一件事是,如果你使用 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.
我的习惯是对原始类型和 C 兼容结构使用
malloc()
,对其他所有内容使用new
。在过去,这提供了与 C 库代码更好的互操作性。在 Linux 上,这仍然是正确的。在 Windows 上,您需要保持分配它的库释放它的习惯。
My habit is to use
malloc()
for primitive types and C compatible structs, andnew
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.
必须使用
malloc
的关键情况是原始代码是否调用realloc
。当然,您可以重新实现所需的所有内容,但这样做并没有多大好处。They key situation in which you must use
malloc
is if the original code ever callsrealloc
. Of course you can reimplement everything needed, but there isn't that much advantage in doing so.一般来说,除非与 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 withdelete
, and what is allocated withmalloc
must be freed withfree
. You cannot allocate withnew
and free withfree()
or vice-versa. So, about the only time you needmalloc
is when you need to pass data off to some C code that mightfree()
orrealloc()
it.