Search code examples
c++classstructallegro5

Port structure to class


I'm using the Allegro 5 framework. When I need to create an event queue I have to call 'al_create_event_queue' and check for errors, and to destroy it 'al_destroy_event_queue'. Since it is the same mechanism I have to use for each object to be created, it is quite boring.

My question is: there is a way to 'port' a structure to a class so that the constructor of my_event_queue actually calls the 'al_create_event_queue' and the destructor calls the 'al_destroy_event_queue'? If not, how could I track object created by these functions so that they are auto-deleted when my 'Game' main handler class is destructed?


Solution

  • Of course you can... simply put the code to create the structure in the constructor, and the code to delete it in the destructor.

    struct MyQueue {
      MyQueue() : queue(al_create_event_queue() { }
      ~MyQueue() { al_destroy_event_queue(queue); }
    
      ALLEGRO_EVENT_QUEUE* queue;
    
    private:
      MyQueue(const MyQueue&);
      MyQueue& operator =(MyQueue);
    };
    

    Note that you can't do too much to wrap these types... you pass around those pointers so much in Allegro code that you basically have to expose the underlying queue object to the world.