【问题标题】:RAII classes for BrewBrew 的 RAII 类
【发布时间】:2011-05-19 16:22:57
【问题描述】:

在使用本地接口时在 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 中调用的通用 Release 函数,而不是特定于接口的版本或其他机制?

--- 编辑 ---- 抱歉,我最初在这篇文章中添加了 C++ 和 RAII 标签,现在我已将其删除。 因为答案需要 Brew 知识而不是 C++ 知识。 感谢花时间回答的人,我应该在开始时添加更多信息而不是添加那些额外的标签。

【问题讨论】:

    标签: brew-framework brewmp


    【解决方案1】:

    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


    编辑这是一个示例:
    #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);
    }
    

    【讨论】:

    • 谢谢,但 Brew 不支持 std/shared_ptr
    • 对不起,我帮不上忙。感谢您更新标签。
    【解决方案2】:

    在析构函数中调用指定函数的 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());
    

    【讨论】:

    • 谢谢,但是在仔细研究了 brew 方面之后,它并不像函数调用那么简单。有一堆#defines 最终减少到以下(简化一点):(TypeName##Vtbl)->Release(pointer)。由于## 字符串化预处理(结果是 T##Vtbl 的字符串化,而不是所需的实际类型名),使用 TypeName 模板不起作用
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-20
    • 2013-04-18
    • 1970-01-01
    • 2020-08-07
    相关资源
    最近更新 更多