Hacker News new | ask | show | jobs
by filthydumbidiot 3932 days ago
By explicitly calling the destructor, you could do away with the requirement that classes must implement a "reset()" member function (which, aside from being an extra step for users, does kind of make RAII in their classes somewhat confusing):

  void release(OBJ* obj) {
    // ...
    obj->OBJ::~OBJ(); // OBJ was the template type
    // ...
  }
acquire() could be improved by using placement new and forwarding the constructor arguments via variadic template:

  template<typename... T>
  OBJ* acquire(T... args) {
    // ...
    return new(mem) OBJ (args...);
  }
Finally, you can exchange potential upfront construction cost (and remove the need for a default constructor in user classes) by making an inner dummy struct that matches the size:

  template<typename OBJ, int32_t NUM_OBJS>
  class Pool {
    struct MockOBJ {
      uint8_t data[sizeof(OBJ)];
    };
    
    public:
      Pool(){
        // ...
        std::for_each(std::begin(_available), std::end(_available),
          [](OBJ*& mem){mem = reinterpret_cast<OBJ*>(new MockOBJ);});
        // ...
      }
  // ...
  };