As we know, std::vector when initialized like std::vector vect(n)
or empty_vect.resize(n)
not only allocates required amount of memory but also initializes it with default value (i.e. calls default constructor). This leads to unnecessary initialization especially if I have an array of integers and I'd like to fill it with some specific values that cannot be provided via any vector constructor.
Capacity on the other hand allocates the memory in call like empty_vect.reserve(n)
, but in this case vector still is empty. So size()
returns 0
, empty()
returns true
, operator[]
generates exceptions.
Now, please look into the code:
{ // My scope starts here...
std::vector<int> vect;
vect.reserve(n);
int *data = vect.data();
// Here I know the size 'n' and I also have data pointer so I can use it as a regular array.
// ...
} // Here ends my scope, so vector is destroyed, memory is released.
The question is if "so I can use it as array" is a safe assumption?
No matter for arguments, I am just curious of above question. Anyway, as for arguments:
- It allocates memory and automatically frees it on any return from function
- Code does not performs unnecessary data initialization (which may affect performance in some cases)