Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

new operator - C++: new call that behaves like calloc?

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

question from:https://stackoverflow.com/questions/808464/c-new-call-that-behaves-like-calloc

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...