gpt4 book ai didi

c++ - 快速新建/删除和分配/释放

转载 作者:太空狗 更新时间:2023-10-29 20:15:11 26 4
gpt4 key购买 nike

我有一个关于 new/delete 运算符与 alloc/free 相比的问题。

当为 char* 动态分配内存时,我通常使用 calloc,因此所有保留位都设置为零,因此我不必为 nulltermination 而烦恼。

char *string = new char[20] 是否只保留 20 个 char 大小的项目,或者它是否也将该内存区域中的所有位设置为零?

如果不能,可以在此内存上使用 memset 来完成吗?如果可以使用 memset 或任何其他方法将分配的内存清零,是否可以重载 new 运算符以让 native char 类型自行完成这项工作?

最佳答案

当您使用时:

string = new char[20];

分配的数组未初始化。为了默认初始化它,你必须使用:

string = new char[20]();  // Allocates and initializes all members to 0

这在 C++03 §5.3.4/15 中有说明:

A new-expression that creates an object of type T initializes that object as follows: ...

If the new-initializer is of the form (), the item is value-initialized (8.5);

关于您的第二个问题 — 是的,您可以使用 memset 将您想要的任何值填充到内存中。

关于c++ - 快速新建/删除和分配/释放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14220573/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com