Search code examples
c++memory-managementmessage-queueglib

GLib Asynchronous Queue with non-POD objects


In a C++ program that uses GLib, it is safe to use non-POD objects with an Asynchronous Queue?

Basically the non-POD object would be passed as gpointer data to

void
g_async_queue_push (GAsyncQueue *queue,
                    gpointer data);

and then retrieved with

gpointer
g_async_queue_pop (GAsyncQueue *queue);

In theory this should never cause problems because a gpointer is just a typedef for void*, so instead of passing POD objects allocated with g_new and freed with g_free I could pass POD objects allocated with new and freed by delete (with proper type casting to avoid this). This implementation is hidden inside my class so I'm the only one in control of the queue.

However, if the queue ever has to internally deallocate a pointer (e.g if after a g_async_queue_unref the queue is destroyed with items still queued), it would call g_free for an object allocated with new and that is bad for many reasons. The documentation for GLib generically says that it's important to match g_new() with g_free() and new with delete.

I know that such a mix of C++ types with a C library should be avoided, but this kind of design consideration is outside the scope of this question.


Solution

  • As long as you create your GAsyncQueue without specifying a free function for the elements (see g_async_queue_new_full()), it’s guaranteed to not free or reallocate the pointers stored in it. They are opaque as far as the queue is concerned.

    You can verify this by looking at the implementation.