operator overloading

Plz any one tell me, what is "(size_t size)" mean in "new" operator overloading?

thanks.

void *operator new (size_t size)
Amount of bytes to allocate.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <cstdlib>

void* operator new(std::size_t sz)
{
    std::cout << "Global new called. Size: " << sz << '\n';
    return std::malloc(sz);
}

void operator delete(void* ptr) noexcept
{
    std::cout << "Global delete called on pointer " << ptr << '\n';
    std::free(ptr);
}

using namespace std;

int main()
{
    int* ip = new int;
    delete ip;
}
Global new called. Size: 4
Global delete called on pointer 0x4859f0

Last edited on
"sz " has value 4, could you plz explain, why ?

Thanks.
Because sizeof(int) is 4 in that particular case.
But sizeof(int) was not mentioned in above program, why ?
ok, got it. I modified this program.

#include <iostream>
#include <cstdlib>

void* operator new(std::size_t size)
{
std::cout << "Global new called. Size: " << size << '\n';
return std::malloc(size);
}

void operator delete(void* ptr)
{
std::cout << "Global delete called on pointer " << ptr << '\n';
std::free(ptr);
}

using namespace std;

int main()
{
char* ip = new char;
delete ip;

system("pause");
}
Just FYI: new int does not just call operator new. It calculates size of data, calls operator new, converts return value to appropriate type, calls object constructor if necessary and then returns resulting pointer.
Last edited on
Topic archived. No new replies allowed.