Getting in the RAII - xfgr.com Click here to Skip to main content

One of Web Biscuit's long-term secret projects is the MidiWrapper, an object-oriented interface for MIDI. A cornerstone of MIDI operations is the HMIDIOUT handle, which requires opening before use, and closing when we're done with it.

This can be done in a RAII class. RAII stands for Resource Acquisition is Initialization, not the snappiest acronym in the whole wide world and not that self explanatory. Basically, we use the guarantee that creating an object always calls a constructor and eventually, a destructor. Played smartly, these two opposing calls can give us automatic Open/Close functionality.

Here's our class:

class CMidiOut
{
public:
    CMidiOut() {}
    ~CMidiOut() {}
private:
    HMIDIOUT m_hMidiOutHandle;
};

We could add Open and Close as public members, but there really is no need. We don't want to burden the creator of our object with things they might forget to do. So let's do it for them:

class CMidiOut
{
public:
    CMidiOut()  :
        m_hMidiOutHandle(nullptr)
    {
        midiOutOpen(
            &m_hMidiOutHandle,  	// Handle
            MIDI_MAPPER,  		// Default device
            NULL,  		// No callback
            NULL,  		// No callback parameters
            CALLBACK_NULL);  	// Flags
    }
    ~CMidiOut()
    {
        if(m_hMidiOutHandle != nullptr)
        {
            midiOutClose(m_hMidiOutHandle);
            m_hMidiOutHandle = nullptr;
        }
    }
private:
    HMIDIOUT m_hMidiOutHandle;
}; 

This is very cute. For a full solution, you'll want an accessor to your handle, and you'll need to prevent or handle copying of your class. These are all exciting subjects we can discuss next time.

You must Sign In to use this message board.
   
Per page   
 FirstPrevNext
GeneralRAII is not about initialisation...
Aescleal
7:58 18 Jun '10  
... it's all about destruction. The idea of RAII is make your code exception resistant and not leak resources when something goes wrong and not have to do the Java dance of try/finally.

Cheers,

Ash

PS: I'm also interested in seeing how you intend to handle errors from midiOutOpen.
GeneralRe: RAII is not about initialisation...
WebBiscuit
8:10 18 Jun '10  
The encapsulation of raw API functions is also nice though.

Error handling shall be done via exceptions, with an errorcode -> exception lookup. This will be a post for the future. I intend to write about most phases of design and development I go through, from the ground up really.
GeneralRe: RAII is not about initialisation...
Aescleal
10:26 18 Jun '10  
Too true, you want to avoid API calls wherever possible, push them to the edge of your code.

And the news that errors from a constructor will pushed out via exceptions sounds like the way to go. I look forward to reading how you develop this in future parts.

Cheers,

Ash


Last Updated 17 Jun 2010 Advertise Privacy Terms of Use