Kelvin  Zhang Kelvin Zhang - 3 months ago 9
C++ Question

How does std::vector destruct its objects?

I'm trying to implement my own std::vector for sake of practice. Current source code:http://pastebin.com/bE4kjzcb




Here is an outline of my class:


  1. Array()
    allocate some memory using
    malloc()

  2. push_back(const T &t)
    add one element, call
    realloc()
    if necessary.

  3. ~Array()
    call
    free()
    to release memory.



The major issue with this model is,
free()
recycles the memory, but it doesn't call
T
's destructor(when
T
is a class rather than standard data type).

This could cause severe resource leak when elements inside vectors are objects. My solution to this problem is, call
~T()
EXPLICITLY before I
free()
the memory.

The reason I'm using
malloc()
is, I'm trying to utilize
realloc()
. If I use
new
and
delete
, memory usage will peak when reallocing. (The moment when both the new buffer and old buffer are present.)

Q:
Is that a bad design? how does
std::vector
resolve this problem? Is there other flaws in my vector class?

PS:Let's not talk about multithread performances of
malloc()
now.

Answer

Calling ~T() is exactly how std::vector handles the problem.

You do however have a couple of problems:

Firstly, push_back needs to use placement new to copy-construct the value into the vector. You can't just use assignment.

Secondly, you can't call realloc - if the object have internal pointers, they are going to end up pointing outside them selves. You must call malloc again, then use placement new to copy-construct the values, then explictly delete all the old values, then call free to release the old value.

(Actually, std::vector doesn't call ~T() itself. Instead it calls the allocator which is responsible for ... allocating and deallocating memory. Internally though, that is how general purpose allocators do it.)

Comments