3
\$\begingroup\$

I started out with this question on Stack Overflow. I have since then gotten an official answer from the mbed developers that the MemoryPool that I was asking about only issued raw C malloc/free type of memory.

Now, I'm thinking about how to create a C++ allocator using the existing MemoryPool. I'm using Google Mock to assist in my development on my desktop machine. I have the following code working with hi-perf dependency injection.

#include <new>
#include <utility>

template <typename T, template <typename O> class Pool>
struct ObjectAllocator {

    template <typename... Args>
    T* alloc(Args&&... args) {
        auto alloc = static_cast<void*>(pool.alloc());
        return alloc ? new(alloc) T(std::forward<Args>(args)...) : nullptr;
    }

    void free(T* object) {
        object->~T();
        pool.free(object);
    }

    Pool<T> pool;
};

Now, I'm wondering if it's really this simple. I'll be compiling for a 32-bit ARM platform with ARM-GCC6. The real memory pool guarantees 4-byte alignment so I believe any object would be safe.

Is there anything that I'm overlooking in this implementation, in terms of whether there are any edge cases that would present problems or need particular attention?

I don't intend to create array types with this implementation.

\$\endgroup\$
  • \$\begingroup\$ Is it a draft, or an actual implementation? That difference is important. Please take a look at the help center. \$\endgroup\$ – Mast Jan 30 '18 at 8:11
  • 1
    \$\begingroup\$ (Welcome to CR!) In my eyes, your edit to revision 3 made this post useful. \$\endgroup\$ – greybeard Jan 30 '18 at 8:23
  • 1
    \$\begingroup\$ Thanks for the pointer, @Mast. It forced me to actually implement and test my draft. \$\endgroup\$ – paulluap Jan 30 '18 at 8:43
  • \$\begingroup\$ Much better :-) \$\endgroup\$ – Mast Jan 30 '18 at 8:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.