开发者

how to use my_alloc for _all_ new calls in C++?

Imagine I'm in C-land, and I have

 void* my_alloc(size_t size);
 void* my_free(void*);

then I can go through my code and r开发者_如何转开发eplace all calls to malloc/free with my_alloc/my_free.

How, I know that given a class Foo, I can do placement new; I can also overload the new operator. However, is there a way to do this for all my C++ classes? (i.e. I want to use my own allocator for new and new[]; but I don't want to run through and hack every class I have defined.)

Thanks!


In global scope,

 void* operator new(size_t s) { return my_alloc(s); }
 void operator delete(void* p) { my_free(p); }
 void* operator new[](size_t s) { return my_alloc(s); }
 void operator delete[](void* p) { my_free(p); }


Define custom global new and delete operator functions :

void* operator new(size_t size) 
{
    //do something
    return malloc(size);
}

void operator delete(void *p) 
{
    //do something     
     free(p); 
}

Placement new can be used when you want to create object from the pre-allocated buffer.

Frequent use of new and delete will cause memory fregmentation and it costs to memory access and allocation.So the whole idea of placement new is to create memory pool at the program start and destroy it at program end and all request for memory just returns free memory location from the pool.


Here is something I found. that may help.

template<typename T>
T* my_alloc(size_t size)
{
    return new T[size];
}

template<typename T>
void my_free(T* ptr)
{
    delete[] ptr;
}

And here is the example used:

int main(void)
{
    char* pChar = my_alloc<char>(10);
    my_free(pChar);
}

Alternative Example:

void* my_alloc (size_t size)
{
   return ::operator new(size);
}

void my_free (void* ptr)
{
   ::operator delete(ptr);
}

All this code should be tested.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜