I have to come in here because some of this isn't correct:
It defeats the purpose of std::vector. Why? Internally, a std::vector allocates a large block of memory. It uses the memory to store any objects that get pushed into the vector. By allocating a new object with each push, you're effectively doubling the memory used by the vector (if the vector is full). std::vector will not automatically de-allocate the memory, so your program will leak. |
This isn't the case. True, vectors allocate memory for each element it contains, but it only allocates memory for the size of it's type. Pointers, no matter what they point to always have the same size, it doesn't matter if it is a pointer to an
int
or a pointer to
MyBigComplexClass
. In either case the vector allocates memory for the size of a pointer and that's it. When the vector goes out of scope it deallocates the memory that it allocated, in this case pointers, which is why you have to free the memory the pointers are referencing yourself before you clear/vector goes out of scope, otherwise you have a leak.
You are not doubling your memory if you are new-ing some big object first, then adding that address to a vector that points to that type, you are only allocating memory for the size of a pointer (as far as the vector is concerned).
For Majin -
arent these pointers the same? So basically when i would now call clear() on the vector with pointers to a few elements - wouldnt that also automatically invalidate pointers in the global vector which contains pointers to all elements? |
No, you are safe doing this. Your "other" vector allocates it's own memory for the pointers, but what they actually refer to are unchanged, when your vector is cleared or goes out of scope, nothing happens to what they were referring to.
Now if you were to delete the memory that was referred to them, through some other vector or your "main" vector, the pointers themselves would be dangling.