Again with templates. Now I'm trying to write a Deleter function class so that it works similar to the language one delete. Here is my attempt:
class Deleter
{
public:
template <typename T>
void operator()(T*) const;
};
template <typename T>
void Deleter::operator()(T* ptr) const
{
std::cout << "freeing memory...\n";
delete ptr;
}
int main()
{
int* pi = new int(7);
char* cp = new char[100];
strcpy(cp, "hi there!");
Deleter del;
del(pi); // 1- argument deduced is int*
del(cp); // 2- argument deduced is char*
std::cout << "\ndone\n";
}
I've overloaded the call operator as a template thus at compile time it knows the static type of argument. (I could made it non-template replacing T with void*).
It works fine but I think surely that statement 2 will cause a Memory leak because I am passing a pointer to a dynamic array into delete which works on pointers to dynamic object not array and as I've already learned it is undefined behavior to call delete on an object that had not been allocated with the corresponding new operator.
So Is there a workaround in my code so that I can call del[]cp;? Thank you!
delete [] ptr;