You cannot use delete
with memory allocated with new[]
, and vice versa using delete[]
with memory allocated with new
. This is exactly why std::unique_ptr
and std::shared_ptr
have specializations to decide when to use delete[]
vs delete
for array and non-array memory, respectively (via the std::default_delete
template).
You are just going to have to specialize your Deleter
in a similar manner, too. Only the user of your Deleter
, not the Deleter
itself, can decide which specialization to use, since only the user has information about how the memory was allocated to begin with, and thus how it needs to be freed.
For example:
template <typename T>
class Deleter
{
public:
void operator()(T* ptr) const {
std::cout << "freeing memory using 'delete'...\n";
delete ptr;
}
};
template <typename T>
class Deleter<T[]>
{
public:
template <typename U>
void operator()(U* ptr) const {
std::cout << "freeing memory using 'delete[]'...\n";
delete[] ptr;
}
};
int main()
{
int* pi = new int(7);
char* cp = new char[100];
strcpy(cp, "hi there!");
Deleter<int> del1;
del1(pi); // uses 'delete'...
Deleter<char[]> del2;
del2(cp); // uses 'delete[]'...
std::cout << "\ndone\n";
}
CLICK HERE to find out more related problems solutions.