Overloading operator delete with additional argument of size_t sz in C++
Asked Answered
C

1

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?

Charlenacharlene answered 13/7, 2023 at 0:48 Comment(1)
Regarding #include <bits/stdc++.h>... and when you combine it with using namespace std;, you can cause some pretty impressive unforced errors. Best to just not use either and avoid unnecessary trainwrecks entirely.Greenbrier
B
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).

Benford answered 13/7, 2023 at 8:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.