You can't do it in one line easily. You can do:
char* c = new char[length];
memset(c, 0, length);
Or, you can overload the new operator:
void *operator new(size_t size, bool nullify)
{
void *buf = malloc(size);
if (!buf) {
// Handle this
}
memset(buf, '\0', size);
return buf;
}
Then you will be able to do:
char* c = new(true) char[length];
while
char* c = new char[length];
will maintain the old behavior. (Note, if you want all new
s to zero out what they create, you can do it by using the same above but taking out the bool nullify
part).
Do note that if you choose the second path you should overload the standard new operator (the one without the bool) and the delete operator too. This is because here you're using malloc()
, and the standard says that malloc()
+ delete
operations are undefined. So you have to overload delete
to use free()
, and the normal new to use malloc()
.
In practice though all implementations use malloc()/free() themselves internally, so even if you don't do it most likely you won't run into any problems (except language lawyers yelling at you)