In C++ there are few compelling reasons to use a C array over std::vector
. One of those few compelling reasons, at least with C++03, was the fact that it is impossible to use a vector to allocate an uninitialized array of objects. The "fill" constructor for std::vector
is:
vector(size_type count, const T& value = T())
Meaning that...
int* array = new array[1000000];
is likely to be much more efficient than:
std::vector<int> v(1000000);
...since the vector constructor will have to zero-initialize the array of integers. Thus, when working with a vector of PODs, there is no real equivalent to malloc
; the best you can get is an equivalent to calloc
.
C++11 seems to have changed this, with the concept of "value-initialization." In C++11, std::vector
has a new constructor which takes a single size_type
value, with no default argument. This "value-initializes" all elements in the vector. The C++11 standard distinguishes between "value-initialization" and "zero-initialization."
My understanding is that "value-initialization" is equivalent to calling the default constructor on T
. If T
is a POD type like int
, then the default constructor simply creates an uninitialized integer. Thus, in C++11, explicit vector::vector(size_type count)
is truly equivalent to malloc
if T
is a POD.
However, my understanding of this is based on the draft C++11 standard, rather than the final standard.
Question: Is my understanding correct here? Does explicit vector::vector(size_type count)
provide an uninitialized array (similar to malloc
) if T
is a POD?
vector::reserve
, as always. – Pubbystd::vector
itself. – Mooing Duckreserve()
and thenpush_back()
? – ipcaligned_storage
. – ipc