1

Say you have a class such as:

template<typename T>
class Foo
{
public:
    T value;
public:
    Foo(const T& value)
    {
        this->value = value;
    }
public:
    ~Foo()
    {
        if(std::is_pointer<T>::value) delete value;
    }
}

Now, obviously the compiler will throw an error if T isn't a pointer. Example:

Foo<int> foo(42);

Is there a way to successfully check if T is a pointer, delete it if it is, without a compiler error?

2 Answers2

0

Use a specialized helper class, something along the following lines:

template<typename T> class delete_me {

public:

   static void destroy(T &value)
   {
   }
};

template<typename P>
class delete_me<P *> {

public:

   static void destroy(P *value)
   {
       delete value;
   }
};

And your destructor:

~Foo()
{
    delete_me<T>::destroy(value);
}
Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148
0

Simply assume that the resource manages itself. If your variable of type T don't free resources, then assume it's the expected behavior.

For example, if you have a non owning pointer that you pass to your class template, you don't want it to delete it, since the pointer is non owning.

On the other hand, a std::unique_ptr will free the pointer it contains automatically.

Let's say you have a singleton Bar, and has a function Bar::instance that returns a Bar*:

// You don't want Foo to delete instance
Foo<Bar*> foo{Bar::instance()};

But with a unique pointer, it will look like this:

Foo<std::unique_ptr<Baz>> foo{std::make_unique<Baz>()};

The pointer to Baz will free itself, just like you intended.

TL; DR You already have the best solution if you simply remove your destructor.

Guillaume Racicot
  • 39,621
  • 9
  • 77
  • 141