0

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)?

melpomene
  • 79,257
  • 6
  • 70
  • 127
BottCode
  • 31
  • 8

2 Answers2

3

Your best option is to use std::unique_ptr<int> or std::shared_ptr<int> as the template argument, i.e. 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.

Community
  • 1
  • 1
R Sahu
  • 196,807
  • 13
  • 136
  • 247
2

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; }
};
Thomas B Preusser
  • 1,139
  • 5
  • 10