RAII classes for Brew

106 Views Asked by At

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.

2

There are 2 best solutions below

1
Juraj Blaho On BEST ANSWER

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());
2
Robᵩ On

shared_ptr does what you ask for:

ISomeInterface* interface = NULL;
int err = ISHELL_Createnstance(…,...,&interface);
std::shared_ptr<ISomeInterface*> pointer(interface, ISomeInterface_Release);

Reference: http://www.boost.org/doc/libs/1_46_1/libs/smart_ptr/shared_ptr.htm#constructors


EDIT Here is a sample:

#include <cstdio>
#include <memory>

int main(int ac, char **av) {
  std::shared_ptr<FILE> file(fopen("/etc/passwd", "r"), fclose);
  int i;
  while( (i = fgetc(file.get())) != EOF)
    putchar(i);
}