6

The code below allows you to see size of variable being deleted:

#include <iostream>
#include <stdlib.h>
using namespace std;

struct P {
    static void operator delete(void* ptr, std::size_t sz)
    {
        cout << "custom delete for size " << sz <<endl;
        delete (ptr); // ::operator delete(ptr) can also be used
    }
    static void operator delete[](void* ptr, std::size_t sz)
    {
        cout << "custom delete for size " << sz <<endl;
        delete (ptr); // ::operator delete(ptr) can also be used
    }
};

int main()
{
    P* var1 = new P;
    delete var1;

    P* var2 = new P[10];
    delete[] var2;
}

Output:

custom delete for size 1
custom delete for size 14

My questions is: Where does argument std::size_t sz get assigned value?

wohlstad
  • 12,661
  • 10
  • 26
  • 39
Aison Li
  • 61
  • 2
  • 4
    [Regarding `#include `...](https://stackoverflow.com/q/31816095/4581301) and when you combine it [with `using namespace std;`](https://stackoverflow.com/q/1452721/4581301), you can cause some pretty impressive unforced errors. Best to just not use either and avoid unnecessary trainwrecks entirely. – user4581301 Jul 13 '23 at 01:06
  • 5
    Whichever C++ textbook taught you to use `` -- you should throw it away and get a different C++ textbook. If you copied that off some web site, without any explanation, don't visit that web site any more. If you saw this in some clown's Youtube video, unsubscribe from that channel, you're not learning proper C++. This is not a standard C++ header file, many C++ compilers don't have it and will not compile the shown code. – Sam Varshavchik Jul 13 '23 at 01:07

1 Answers1

1
Where does argument std::size_t sz get assigned value?

The compiler does that. The expression delete var; has two parts - first the destructor for P (if any) is called, and then operator delete is called with parameters supplied by the compiler.

Despite their similar names, "the delete operator" and "operator delete" are two different things.

(And Bjarne has said that he is sorry to not have come up with better names).

BoP
  • 2,310
  • 1
  • 15
  • 24