Feb 11, 2015 at 7:45am UTC
Plz any one tell me, what is "(size_t size)" mean in "new" operator overloading?
thanks.
void *operator new (size_t size)
Feb 11, 2015 at 8:48am UTC
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 Feb 11, 2015 at 8:56am UTC
Feb 11, 2015 at 9:25am UTC
"sz " has value 4, could you plz explain, why ?
Thanks.
Feb 11, 2015 at 9:26am UTC
Because sizeof (int )
is 4 in that particular case.
Feb 11, 2015 at 9:31am UTC
But sizeof(int) was not mentioned in above program, why ?
Feb 11, 2015 at 9:34am UTC
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");
}
Feb 11, 2015 at 9:37am UTC
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 Feb 11, 2015 at 9:38am UTC