-1

I was overloading a delete operator in C++, I used free() for this:

class A
{
private:
    int x;
    int y;
public:
    void operator delete(void* ptr)
    {
        free(ptr);
    }

    void operator delete[](void* ptr)
    {
        free(ptr);
    }
}

int main()
{
    A *a = new A();
    A *b = new A[10];

    delete a; // This should free 8 bytes
    delete b; // This also 8 only

    delete[] b;// This should free 80 bytes

    return 0;
}

how free do this job

As I know dynamic allocation store what size allocated as hidden so while deallocation it use from there

but when we use delete b; or delete[] b; hidden allocation says alwyas 80 then how 8 only get de-allocated.

If its not correct way then how we can overload delete operator using free?

David G
  • 94,763
  • 41
  • 167
  • 253
  • First off, these aren't overloads but replacements. You also need to mske sure that you match you custom versions of `operator delete()` with a custom version of `operator new()` (likewise for the array versions). – Dietmar Kühl Dec 21 '14 at 14:21
  • @Peter I hope it’s irony that your comment doesn’t either. ;-) – Konrad Rudolph Dec 21 '14 at 14:31

3 Answers3

3

Using delete array with a pointer which was obrained using with new T[n] (for some type T and some type n) results in undefined behavior.

Dietmar Kühl
  • 150,225
  • 13
  • 225
  • 380
0

delete b also knows the size that was allocated as you expect from delete[] b

Using delete b in the place delete [] b could lead to undefined behavior. The aspect that you miss out on is that the destructors of individual objects in the array won't be called, if you don't use delete[].

Instead of repeating (many) earlier answers here, please search on StackOverflow.

Here is one: delete vs delete[] operators in C++

Community
  • 1
  • 1
KalyanS
  • 527
  • 3
  • 8
0

new and delete are a tightly coupled pair of operations. It's not correct to overload only one of them, since they are two halves of the same object allocation scheme.

The default new and delete implementations are unspecified in the standard and therefore implementation-defined.

It may be that default new uses malloc() to allocate memory on your system, but then it may not be.

Richard Hodges
  • 68,278
  • 7
  • 90
  • 142