Search code examples
c++smart-pointersallegroallegro5

How to use use smart pointers with Allegro Bitmaps?


I've decided I'm tired of deciding which classes are responsible for deleting which bitmaps. I've tried to rewrite my code to use smart pointers with a custom deleter al_destroy_bitmap

My code is pretty simple.

shared_ptr<ALLEGRO_BITMAP> test = make_shared<ALLEGRO_BITMAP>(al_load_bitmap("hello.png"), al_destroy_bitmap);

I'm getting quite a few errors which I just can't seem to work around.

error C2079: 'std::_Get_align<ALLEGRO_BITMAP>::Elt2' uses undefined struct 'ALLEGRO_BITMAP'
error C2079: 'std::_Get_align<ALLEGRO_BITMAP>::Elt0' uses undefined struct 'ALLEGRO_BITMAP'
error C2027: use of undefined type 'ALLEGRO_BITMAP'
error C2027: use of undefined type 'ALLEGRO_BITMAP'

Other solutions to solve my problem would be creating a Bitmap class to wrap all of the Allegro stuff, but that seems ugly, and I don't think I should have to do that. Plus I already use other allegro functions everywhere, and then I would want to then write those same types of classes for ALLEGRO_SAMPLE and ALLEGRO_FONT. I really don't feel like doing that.

How can I use smart pointers with Allegro bitmaps?

Edit: Perhaps to give non-Allegro coders a feel for how ALLEGRO_BITMAPs work, I'll post a little code below

ALLEGRO_BITMAP *test = al_load_bitmap("hello.png") // This works
ALLEGRO_BITMAP test1; // This fails with error C2079 undefined struct ALLEGRO_BITMAP. I expect this here.

Solution

  • Like this:

    std::shared_ptr<ALLEGRO_BITMAP> test(al_load_bitmap("hello.png"), al_destroy_bitmap);
    

    Remember: make_shared and make_unique call new, you don't want that here.

    Also make_x<T> constructs an object of type T, passing the given arguments to T's constructor. But al_load_bitmap returns a pointer to a fully constructed object so you don't want to call any constructor (except the smart pointer constructor).