C ++:新的调用,像calloc一样? [英] C++: new call that behaves like calloc?

查看:174
本文介绍了C ++:新的调用,像calloc一样?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以调用 new 让它清空内存,如 calloc

Is there a call I can make to new to have it zero out memory like calloc?

推荐答案

与他们的答案中有些人说的相反,是可能的。

Contrary what some are saying in their answers, it is possible.

char * c = new char[N]();

将零初始化所有字符(实际上,它被称为值初始化,但值初始化将对标量类型数组的所有其成员进行零初始化)。如果这是你的后。

Will zero initialize all the characters (in reality, it's called value-initialization. But value-initialization is going to be zero-initialization for all its members of an array of scalar type). If that's what you are after.

值得注意的是,它也适用于没有用户声明构造函数的类类型数组,在这种情况下,它们的任何成员都是值初始化的:

Worth to note that it does also work for (arrays of) class-types without user declared constructor in which case any member of them is value initialized:

struct T { int a; };
T *t = new T[1]();
assert(t[0].a == 0);
delete[] t;

这不是一些扩展或东西。它的工作和行为方式在C ++ 98中也是一样。只是在那里它被称为默认初始化而不是值初始化。然而,在标量或标量或POD类型的数组的两种情况下都进行零初始化。

It's not some extension or something. It worked and behaved the same way in C++98 too. Just there it was called default initialization instead of value initialization. Zero initialization, however, is done in both cases for scalars or arrays of scalar or POD types.

这篇关于C ++:新的调用,像calloc一样?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆