Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class specific new/delete

Tags:

c++

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.

like image 916
pic11 Avatar asked Dec 17 '11 06:12

pic11


People also ask

Why overload new and delete?

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.

What is the difference between new and delete operator?

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.

What is :: operator new?

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.

What happens when we use new and delete operator?

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.


1 Answers

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*);
};
like image 166
Igor Avatar answered Sep 19 '22 19:09

Igor