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
?
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With