Is it possible to overload class specific new/delete that is called when arrays of objects are created.
class Foo;
Foo* f = new Foo[10]; // calls overloaded new
delete[] f; // calls overloaded delete
Thank you.
The most common reason to overload new and delete are simply to check for memory leaks, and memory usage stats. Note that "memory leak" is usually generalized to memory errors. You can check for things such as double deletes and buffer overruns.
The main difference between new and delete operator in C++ is that new is used to allocate memory for an object or an array while, delete is used to deallocate the memory allocated using the new operator. There are two types of memory as static and dynamic memory.
operator new, operator new[] Attempts to allocate requested number of bytes, and the allocation request can fail (even if the requested number of bytes is zero). These allocation functions are called by new-expressions to allocate memory in which new object would then be initialized.
Memory that is dynamically allocated using the new operator can be freed using the delete operator. The delete operator calls the operator delete function, which frees memory back to the available pool. Using the delete operator also causes the class destructor (if one exists) to be called.
Yes, it is possible. There is a tutorial about overloading new
and delete
here, and there is a nice example of overloading new
and delete
for array, here.
class Myclass
{
public:
void* operator new(size_t);
void operator delete(void*);
void* operator new[](size_t);
void operator delete[](void*);
};
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