Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting a Template Type

I have a generic class that looks something like this:

template <class T>
class Example
{
  private:
    T data;
  public:
    Example(): data(T())
    Example(T typeData): data(typeData) 
    ~Example()

    // ...
};

I'm a bit confused about how to implement a deconstructor for something like this. Specifically, since T is of any type, it could be memory allocated on the stack (which is always the case for Example's created via the no-argument constructor) or on the heap.

For instance, if the client makes the type for T an int* and provides a pointer to dynamic memory, how do I know to call delete on data as opposed to if the client set the type to int?

like image 750
nmagerko Avatar asked Feb 09 '16 16:02

nmagerko


1 Answers

The simplest answer is: don't. Don't try to second-guess the user and do something they might not expect. Adopt the same policy as standard containers do: assume T cleans up after itself correctly.

If the client code is written correctly, it will use RAII classes (such as smart pointers) for automatic and correct management of memory and other resources. If it's not, you cannot hope to fix that in your provider code.

Make your class work with std::unique_ptr and std::shared_ptr, as well as any other custom RAII class, and let your clients do the management themselves. What if they want to store non-owning pointers, after all?

like image 124
Angew is no longer proud of SO Avatar answered Oct 11 '22 07:10

Angew is no longer proud of SO