News for hackers. Stuff that matters.
Re:Hourglass Interfaces for C++ APIs by blt on Friday September 12, 2014 @05:04PM (#8310458)
I've seen a lot of tutorials in this style, but they all fall short in one major way: the user is forced to let the library take care of memory allocation.

What if I want to create and destroy the library's objects over and over using the same memory?

I'm surprised we don't see more libraries like this: (of course, in real life the function bodies would not be inline in the header.)

    size_t hairpoll_size() { return sizeof(Poll); }
    void hairpoll_construct(void *mem, char const *person) { new (mem) Poll(person); }
    void hairpoll_destruct(void *mem) { ((Poll *)mem)->Poll::~Poll(); }

    void *poll_reusable = malloc(hairpoll_size());
    while (a long time) {
        char const *person = get_person_name();
        hairpoll_construct(poll_reusable, person);
        // use the hairpoll
        hairpoll_destruct(poll_reusable);
    }
    free(poll_reusable);
Yeah, it's complex and it loses type safety, but if you're already wrapping in a client-side C++ library that will be hidden from the user.

There are no comments on this comment yet.