As already mentioned, std::vector is usually the way to go. The reason is that the vector is very well understood, it is standardized for all compilers and platforms, and, above all, it protects the programmer from the difficulties of manual memory management. Moreover, vector elements must be selected sequentially (that is, vector elements A, B, C will be displayed in continuous memory in the same order in which they were entered into the vector). This should make the vector as cache-friendly as a regular dynamically distributed array.
While the same end result can be determined by declaring a pointer to int and manual memory management, this would mean additional work:
- Each time you need more memory, you must manually allocate it
- You must be very careful to delete previously allocated memory before assigning a new value to the pointer so that you are not stuck in huge memory leaks.
Unlike std::vector , this approach is not RAII - friendly. Consider the following example:
void function() { int* array = new int[32]; char* somethingElse = new char[10];
It looks healthy and safe. But this is not so. What if, when I try to allocate 10 bytes for "somethingElse", the system runs out of memory? An exception of the std::bad_alloc type will be std::bad_alloc , which will begin to spin the stack looking for the exception handler, skipping the delete statements at the end of the function. You have a memory leak. This is just one of many reasons to avoid manually managing memory in C ++. To fix this (if you really want it), the Boost library provides a bunch of good RAII wrappers like scoped_array and scoped_ptr .
source share