当在Brew中使用本地接口时,在其中编写代码可能会重复且容易出错,从而使其健壮,例如:
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....编写一个RAII类在退出函数时自动释放接口会很快,但它将特定于特定的接口(当然,它会在其析构函数中调用ISomeInterface_Release )。
有没有办法制作一个泛型的RAII类,可以用于不同类型的接口?也就是说,是否存在可以在RAII中调用的通用发布函数,而不是特定于接口的发布,或者某种其他机制?
-编辑-抱歉,我最初在这篇文章中添加了C++和RAII标签,现在我已经删除了这些标签。因为答案需要Brew知识,而不是C++知识。感谢那些花时间回答的人,我应该在一开始就添加更多的信息,而不是添加那些额外的标签。
发布于 2011-05-20 00:32:59
在析构函数中调用指定函数的RAII类可能如下所示:
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); }
//...
};然后,您只需传递一个类型T (例如,Foo*)和一个可以通过类型为T的单个参数调用的函数,并释放该对象。
scope_destroyer<Foo, &ISomeInterface_Release> foo(CreateFoo());发布于 2011-05-20 01:18:10
shared_ptr会按照您的要求进行操作:
ISomeInterface* interface = NULL;
int err = ISHELL_Createnstance(…,...,&interface);
std::shared_ptr<ISomeInterface*> pointer(interface, ISomeInterface_Release);参考:http://www.boost.org/doc/libs/1_46_1/libs/smart_ptr/shared_ptr.htm#constructors
EDIT示例如下:
#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);
}https://stackoverflow.com/questions/6061727
复制相似问题