Search code examples
brew-frameworkbrewmp

RAII classes for Brew


Writing code in Brew when local interfaces are being used in it can be repetitive and error prone to make it robust, i.e.:

Foo()
{
ISomeInterface* interface = NULL;
int err = ISHELL_Createnstance(…,...,&interface);

err = somethingThatCanFail();
if (AEE_SUCCESS != err)
    ISomeInterface_Release(interface);

err = somethingElseThatCanFail()
if (AEE_SUCCESS != err)
    ISomeInterface_Release(interface);

etc....

It would be quick to write an RAII class to automatically release the interface on exit from the function, but it would be specific to a particular interface (it would of course call ISomeInterface_Release in its destructor)

Is there any way of making a generic RAII class that can be used for interfaces of different types? i.e. is there a generic Release function that could be called in the RAII instead of the interface specific release, or some other mechanism?

--- Edit ---- Apologies, I originally added the C++ and RAII tags to this posting which I've now removed. As the answer requires Brew knowledge not C++ knowledge. Thanks to the people who took the time to answer, I should have added more info to begin with and not added those additional tags.


Solution

  • The RAII class that calls a specified function in destructor may look like this:

    template<typename T, void (*onRelease)(T)>
    class scope_destroyer {
        T m_data;
    
    public:
        scope_destroyer(T const &data) 
            : m_data(data)
        {}
    
        ~scope_destroyer() { onRelease(m_data); }
    
        //...
    };
    

    Then you just pass a type T (e.g. a Foo*) and a function that can be called with a single parameter of type T and releases the object.

    scope_destroyer<Foo, &ISomeInterface_Release> foo(CreateFoo());