Allegro.cc - Online Community

Allegro.cc Forums » Programming Questions » Shared_ptr with event queues

This thread is locked; no one can reply to it. rss feed Print
Shared_ptr with event queues
Addison Elliott
Member #12,394
November 2010

So I just recently decided to switch to smart pointers in my multithreaded client. I am currently having problems since pointers(shared_ptr) through the event queue. (By this I mean user events). I did try using a shared_ptr pointer, but that gave me a segmentation fault when I had another shared_ptr inside the shared_ptr structure. Here's an example on what I mean since it sounds a bit confusing:

#SelectExpand
1struct Bitmap 2{ 3 std::shared_ptr<ALLEGRO_BITMAP> bitmap; 4}; 5 6std::shared_ptr<Bitmap> variable(new Bitmap()); 7ALLEGRO_EVENT event; 8event.type = USER_EVENT_BITMAP_LOAD; 9event.user.data1 = &variable; 10al_emit_user_event(eventSrc, &event, NULL); 11------------------------------------------------------------ 12std::shared_ptr<Bitmap> bitmap = *((std::shared_ptr<Bitmap> *)event.user.data1); 13// This is where I get a segmentation fault because of the shared_ptr inside the Bitmap structure.

My main question that I am asking is, what is a way to pass a smart pointer through a event queue? If the best way is to use a shared_ptr pointer like I did, could someone please explain how I could fix the segmentation fault?

bamccaig
Member #7,536
July 2006
avatar

The entire purpose of a shared_ptr is to destroy the object when all pointers to it are destroyed. As a rule, you should never take the address (pointer to) a smart pointer. :P That defeats the purpose. I don't think you're going to be able to use a smart pointer for this without negating the purpose of having a smart pointer in the first place. :P You're unfortunately going to have to manage the memory yourself.

The internal shared_ptr is fine (Bitmap::bitmap), but the stack-allocated smart pointer variable will be destroyed as soon as it goes out of scope. As a consequence, it will also destroy the Bitmap inside of it, and the Bitmap::bitmap inside of that.

Addison Elliott
Member #12,394
November 2010

Eh you're breaking my heart :( I was hoping for a 1 line fix :P
I'll look it over in the morning and look for other options.

Edgar Reynaldo
Major Reynaldo
May 2007
avatar

Well, a shared pointer will just not work here, at least not inside of the event itself.

Something more like :

ALLEGRO_USER_EVENT usr;
usr.type == USER_EVENT_BITMAP_LOAD;
usr.user.data1 = (int*)al_load_bitmap(Path);
al_emit_user_event(event_source , &usr , NULL);

//...

al_wait_for_event(event_queue , &event);
if (event.type == USER_EVENT_BITMAP_LOAD) {
   my_bitmaps_vector.push_back(shared_ptr<ALLEGRO_BITMAP>((ALLEGRO_BITMAP*)event.user.data1));
}

Your ALLEGRO_BITMAP* will be temporarily unavailable to destroy until you retrieve the event itself.

Go to: