I have a template class myFoo that stores "stuff" of type T, which can be either primitive or a pointer to complex types. When myFoo is deleted, I want to free all the memory associated with everything that it stores. This means that I need to call delete on every saved pointer, but I can also end up calling delete on the primitive. It is safe?
I have included the myFoo sketch below to better highlight what is happening. I am not sure that the behavior of the destructor is well defined.
template<class T>
class myFoo
{
public:
myFoo(int size)
{
size_ = size;
T* foo = new T[size_];
}
void addFoo(T tmp, int index)
{
foo[index] = tmp;
}
virtual ~myFoo()
{
for(int i=0; i < size_; i++)
{
delete foo[i];
}
delete [] foo;
}
private:
int size_;
T* foo;
}
source
share