Original Post
Hi, I'm currently working on getting my libraries to use an allocator that might be provided by client code. The allocator basically supports functions like void* allocate(size_t) and void free(void*). Using it could be done as follows: 1. override new and delete for the library's namespace, i.e. 2. override new and delete on a per-class basis if needed 3. provide placement new and delete that take the allocator However, there are some questions that I couldn't answer satisfyingly: 1. Would the overridden new and delete in the lib's namespace only be used for objects from that namespace? 2. With overriding new and delete per class I'd have a problem if I needed to dynamically allocate memory for classes from outside the lib (e.g. new vector<...>()). I guess I could use placement new in that case (new (allocator.allocate(...)) vector<...>()) but the problem is what size should I allocate for? Would sizeof(XXX) be sufficient in all cases, or could the size returned be too small? 3. I could have all allocations done via placement new within the lib (and provide factory methods that take care of this for objects uses outside the lib). However, since there isn't a placement delete that the client can safely use (the destructor would not be called) and I can't assure that the client doesn't simply do "delete p;" the only solution I see atm is to force the client to use library methods for destruction that take care of calling the destructor and the correct placement delete (especially since the correct allocator is normally only known within the library). From what I know now, I would go as follows: 1. use placement new/delete for all allocations within the library (except for STL/boost containers that get their own custom allocator [wrapper] ) 2. force the client to use methods for construction/destruction of library objects that are directly usable by the client Is this a good approach or are there any flaws that I don't see right now? How is this generally done in C++ libs? Thanks in advance, Thomas
namespace lib
{
void* operator new(std::size_t) throw (std::bad_alloc)
{
//allocate memory using the custom allocator
}
...
}