In C++11 when I allocate a dynamic array using T *array = new T[n]; it’s already zeroed (using gcc 4.7.2, Ubuntu 12.10 64bit).
- Is this forced by the C++11 specification?
- How can one allocate an array without zeroing its items? This should be probably a little bit faster.
Edit: I’ve checked that for T = int.
gcc cxx-flags: -std=gnu++11 -O3 -ffast-math -fno-rtti
§ 5.3.4
new-initializer is the
()innew T[] (), which you have omitted.§ 8.5 / 6
int[] is default initialized -> each element is default-initialized.
“Is this forced by the C++11 specification?”: “no initialization is performed”, so no, zeroing is not forced if T has no zeroing constructor (i.e. T is a POD). For T=int, no zeroing has to be performed.
Why is it zero anyway? If your program allocates new memory from the operating system, the OS zeroes the new memory for you. It would be very dangerous, if you could read memory of another program, which possibly stores sensible data. However, if you write into that memory, free it and allocate some of it again, it should not be zeroed.