I have template class Array
where the template type T
should be either pointer or not-pointer type.
template<class T>
class TArray
{
static const int max_len=100;
T* data;
int length;
public:
TArray(){data=new T[max_len]; this->length=0;}
void Add(T value){data[length++]=value;}
~TArray();
};
The problem is how to free space, since we can not call delete
for not pointer types like this
template<class T>
TArray<T>::~TArray()
{
//for(int i =0; i < length; i++)
// delete data[i]; // NOT WORKING WITH OBJECTS THAT ARE NOT POINTERS !!!
delete[] data;
}
Let's have addition class
class A
{
int* a;
public:
A(int n){a = new int[n];}
~A(){delete[] a;}
};
and make two instances of template class
// Create array of doubles
TArray<double>* double_array = new TArray<double>();
delete double_array;
// Create array of pointers to class A
TArray<A*>* A_array = new TArray<A*>();
A* a = new A(5);
A_array->Add(a);
delete A_array;
When I call destructor for TArray<A*>
I need to call destructor for class A
but I don't know how, since the commented code in destructor is not compile (C2541) if we make for example array of doubles.
Inside the destructor, you can use
std::is_pointer
and onlydelete[]
the data then.The preferred alternative is to not manage memory yourself though (use
std::vector
or smart pointers).You can develop two versions for your template. First, write the normal version
template<class T>
. Then, write a second pointer-only version that specializes your template by declaring it like this:If you replace the raw pointers with
std::unique_ptr
orstd::shared_ptr
, the problem vanishes.(If that's not what you want, then think twice about whether
TArray
should be managing this at all. Who will guarantee that the pointers stored in aTArray<T*>
have been allocated withnew
? There's no RAII solution to that problem.)