Destructor in template class c : How to delete fie

2019-05-14 20:43发布

问题:

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.

回答1:

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:

template<class T>
class TArray<T*>


回答2:

Inside the destructor, you can use std::is_pointer and only delete[] the data then.

The preferred alternative is to not manage memory yourself though (use std::vector or smart pointers).



回答3:

If you replace the raw pointers with std::unique_ptr or std::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 a TArray<T*> have been allocated with new? There's no RAII solution to that problem.)