I am trying to write a custom allocator for a particular class. My experience with allocators is basically none, so this might be obvious.
I wish my allocations to be dependent on certain parameters. Roughly speaking, I wish to have multiple memory managers, each managing a few objects. When creating the objects, I shall know which manager the object should belong to. Having read up a fair bit on overloading operator new
, I am lost as to how I can implement what I need.
This page says that there is a version of operator new
that accepts user defined parameters, but it seems this version would not be called while allocating objects using new
. Could somebody point out how to construct anything other than a global allocator? On a related note, how can I call parameterized constructors if I am using overloaded class-specific operator new
?
You can create a customized allocator that takes in extra parameters by defining an overload for operator new
like this:
void* operator new (size_t size, /* extra parameters here */) {
/* Do something, then return a pointer to at least 'size' bytes. */
}
You can then use your allocator by writing
MyObject* obj = new (/* extra params */) MyObject(/* constructor args */);
For example, here's a silly custom allocator that prints out a message when you allocate something:
void* operator new(size_t numBytes, const std::string& message) {
std::cout << "Custom message: " << message << std::endl;
/* Use the default allocator to get some bytes. */
return ::operator new(numBytes);
}
You could call it by writing
std::complex<double>* obj = new ("Hello, world!") std::complex<double>(0.0, 0.0);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With