K6L2
K6L2

Reputation: 21

What's the best way to handle pointer & non-pointer template types in a custom std::vector-like container?

So I'm building my own dynamic array container similar to std::vector for fun/research. A stripped down header for my container looks like this:

template<class ElementClass> 
class Array
{
public:
    Array(class Allocator* allocator, size_t initialCapacity);
    ~Array();

    ...

private:
    class Allocator* allocator;
    ElementClass* pFirst;
    size_t m_capacity;
    size_t m_size;
};

So far my Array class is working nicely with any type I provide to the template (woohoo!). However, my current implementation seems to choke hard when I try to use a pointer instead of an object type. A good example of this would be in the destructor:

template<class ElementClass>
Array<ElementClass>::~Array()
{
    for (size_t c = 0; c < m_capacity; c++)
    {
        pFirst[c]->~ElementClass();
    }
    allocator->free(pFirst);
}

This obviously results in a nasty error, because if I were to make an Array<int*> for example, then ElementClass translates to int*, which the compiler rightfully trips on and proceeds to fall down a long set of stairs. Also there are a few other places where this sort of thing happens, but I left those out for brevity.

So my question is: what is the correct way to handle this template class such that it allows me to create a template container that can handle pointers as well as non-pointer types? Am I supposed to use some kind of template specialization technique for the functions where this sort of issue arises? Thanks in advance. :)

Upvotes: 0

Views: 116

Answers (1)

robthebloke
robthebloke

Reputation: 9682

What you appear to be doing is calling the dtor on the element pointed to by the pointer, rather than the pointer values stored in the array. If your array is doing anything other than this in the dtor, it's doing it wrong....

template<class ElementClass>
Array<ElementClass>::~Array()
{
    for (size_t c = 0; c < m_size; c++)
    {
        pFirst[c].~ElementClass();
    }
    allocator->free(pFirst);
}

To call the dtor on the objects pointed to by the pointers in the array seems highly dangerous to me. Who knows where those pointers have come from (NULL, stack allocated variables, etc).

Array is "error C2325: 'int *': unexpected type to the right of '->~': expected 'int'".

ElementClass is of type int*. You are attempting to dereference that pointer, so now the type is int. You then are attempting to call the dtor for type int* on an int.

Upvotes: 1

Related Questions