You cannot do this in one line easily. You can do:
char* c = new char[length]; memset(c, 0, length);
Or you can overload the new statement:
void *operator new(size_t size, bool nullify) { void *buf = malloc(size); if (!buf) {
Then you can:
char* c = new(true) char[length];
but
char* c = new char[length];
will support the previous behavior. (Note: if you want all new nullify what they create, you can do it using the same thing, but taking out the bool nullify part).
Please note: if you choose the second path, you must overload the standard new operator (the one that does not have bool), and the delete operator. This is because you are using malloc() , and the standard states that malloc() + delete undefined operations. So you need to overload delete to use free() , and the usual new one is malloc() .
In practice, although all implementations use malloc () / free () internally, therefore, even if you do not, you will most likely not encounter any problems (except that lawyers in the language yell at you)
Andreas Bonini Jan 08 '10 at 18:14 2010-01-08 18:14
source share