Thursday, July 25, 2013

Custom New + Delete (Part 1)

The motivation behind wanting to learn this is:

1) Better understand how operator new works.
2) Build up towards custom allocation for fast pimpl's.
3) It's pretty cool.

For my first test of trying to understand how the custom new/delete worked, I implemented a small program. My preliminary search for custom new/delete didn't turn up a simple example, so here it is:


#include <iostream>
#include <string>

struct S
{
S() : value(13), message("Hello World!") { }
int value;
std::string message;

void* operator new(size_t i) 
{
std::cout << "CALLING CUSTOM NEW!" << std::endl;
return new char[i];
}

void operator delete (void* ptr)
{
std::cout << "CALLING CUSTOM DELETER!" << std::endl;
delete[] reinterpret_cast<char*>(ptr);
}
};


int main(int argc, char** argv)
{
    for(;;)
    {
S* s = new S();
std::cout << "s.value = " 
                  << s->value 
                  << ", s.message = " 
                  << s->message 
                  << std::endl;
delete s;
    }
}

Doesn't get much simpler. The points of understanding for this are:

1) operator new DOES NOT invoke the constructor! It merely allocates the memory that is later filled by the constructor. 

2) Always have a corresponding operator delete.

It's really that simple. I ran this program and watched the memory consumption using top. It didn't seem to budge so that made me feel good. 

No comments:

Post a Comment