Skip to main content
GameDev.net gamedev.net
🔒 Locked

using client allocator in library

Started by Lord_Evil Aug 21, 2009 at 3:35 AM 0 replies 1.1k views
Original Post
Lord_Evil
Lord_Evil
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.

namespace lib
{
  void* operator new(std::size_t) throw (std::bad_alloc)
  {
    //allocate memory using the custom allocator
  }
  ...
}

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
If I was helpful, feel free to rate me up ;)If I wasn't and you feel to rate me down, please let me know why!
Lord_Evil
Lord_Evil
Since nobody complains about my approach I guess it is sensible, except that new and delete cannot be overridden per namespace but only globally or per class (although overriding globally using a namespace specific allocator should work like overriding per namespace).
If I was helpful, feel free to rate me up ;)If I wasn't and you feel to rate me down, please let me know why!

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.