简体   繁体   中英

destructor of template class with pointer

I have a question. Consider this template class

template<class T> 
class nodo{
public:
    T data;
};

Let's suppose that I'm not redefining the destructor. If we suppose that T=int, the standard destructor deallocates data. But what happens if T=int* ? Is just the pointer going to be deallocated or the object pointed too? In theory just the pointer.

How can I deallocate the object pointed to? In the end, how can I write the destructor of a template class that has a template parameter that could be a pointer (and so of an explicit deallocation)?

Your best option is to use std::unique_ptr<int> or std::shared_ptr<int> as the template argument, ie use

nodo<std::unique_ptr<int>> n1;

instead of

nodo<int*> n1;

You can try something like:

// Noop deleter
template <typename T> struct deleter
{
   void operator()(T& ptr) {}
};

// deleter that does something
template <typename T> struct deleter<T*>
{
   void operator()(T* ptr) { delete ptr; }
};


template<class T> 
class nodo{
public:
   using deleter_t = deleter<T>;
    T data;

    ~nodo()
    {
       deleter_t()(data);
    }
};

However, then you have to worry about another can of worms. What happens when nodo is copy-constructed or assigned to another nodo object? You need to take care of all the issues that make The Rule of Three and The Rule of Five relevant.

What you need is a partially specialized template for pointer types:

template<typename T> class Test {
  T  val;
public:
  Test(T const &v) : val(v) {}
};

// Specialize for pointers
template<typename T> class Test<T*> {
  T* val;
public:
  Test(T* v) : val(v) {}
  ~Test() { delete  val; }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM