Nikita
Nikita

Reputation: 185

Own custom vector class. Memory reallocation

I want to implement my own simple vector class. This vector should support pushing new elements (of type T) even if reserved memory is exhausted. So, I need to allocate a new block of memory, copy elements to it and then free the old memory block.

If I create a block of memory using new T[] then I must free it using delete[], which will make constructors of each element in the vector to be called. I don't want that because I think of just copying the old vector using memcpy().

So I came up with a decision to allocate memory using new char[] and use placement new to fill the array. When I need to reallocate the reserved memory I just use memcpy() on that block of memory and then free it using delete[].

Is this a reasonable solution?

Upvotes: 3

Views: 153

Answers (1)

Max Langhof
Max Langhof

Reputation: 23691

There are only certain objects that should (as in, are allowed to) be "copied" via memcpy. These are called trivial types - which cannot have custom destructors.

Thus, using memcpy to avoid calling destructors is contradictory. You're only allowed to do the former if the latter is unnecessary.

Consider this: In general, a T may have pointers/references to its own members (or other T in the same vector). If you move these objects around with memcpy, these will keep referring to the old (now invalid) memory locations. This is exactly what the constructors and destructors of T have to handle (if copying/moving them is even allowed), so omitting them will lead to problems.

Upvotes: 6

Related Questions