7

我为初始化和释放资源的 C 函数对编写了一个 RAII 包装器,它在大多数情况下都能很好地为我服务。

#include <GL/glfw.h>
#include <string>
#include <functional>
#include <stdexcept>

template <typename UninitFuncType,
          typename SuccessValueType,
          SuccessValueType successValue>
class RAIIWrapper
{
public:
    template <typename InitFuncType, typename... Args>
    RAIIWrapper(InitFuncType initializer,
                UninitFuncType uninitializer,
                const std::string &errorString,
                const Args&... args) : 
        uninit_func(uninitializer)
    {
        if (successValue != initializer(args...))
            throw std::runtime_error(errorString);
        initialized = true;
    }

    bool isInitialized() const
    {
        return initalized;
    }

    ~RAIIWrapper()
    {
        if (initalized)
            uninit_func();
    }

    // non-copyable
    RAIIWrapper(const RAIIWrapper &) = delete;
    RAIIWrapper& operator=(const RAIIWrapper &) = delete;

private:
    bool initalized = false;
    std::function<UninitFuncType> uninit_func;
};

using GLFWSystem = RAIIWrapper<decltype(glfwTerminate), decltype(GL_TRUE), GL_TRUE>;
using GLFWWindow = RAIIWrapper<decltype(glfwCloseWindow), decltype(GL_TRUE), GL_TRUE>;

int main()
{
    GLFWSystem glfw(glfwInit,
                    glfwTerminate,
                    "Failed to initialize GLFW");
}

但是,比如说当一个函数返回时,voidEnter/LeaveCriticalSection不确定如何在这个类中进行操作。我应该专门针对SuccessValueType = void案例的课程吗?或者具有默认模板参数的东西应该做什么?

4

2 回答 2

5

我想指出,

  1. 您不需要有关包装类中的初始化函数的信息。您只需要了解未初始化功能。

  2. 您可以创建函数助手来实例化您的包装器。

我想出了以下解决方案(我喜欢@ipc 异常处理的想法)

template <typename UninitF>
struct RAII_wrapper_type
{
    RAII_wrapper_type(UninitF f)
    :_f(f), _empty(false)
    {}
    RAII_wrapper_type(RAII_wrapper_type&& r)
    :_f(r._f), _empty(false)
    {
      r._empty = true;
    }

    RAII_wrapper_type(const RAII_wrapper_type&) = delete;
    void operator=(const RAII_wrapper_type&) = delete;

    ~RAII_wrapper_type()
    {
      if (!_empty) {
        _f();
      }
    }

  private:
    UninitF _f;
    bool _empty; // _empty gets true when _f is `moved out` from the object.
};

template <typename InitF, typename UninitF, typename RType, typename... Args>
RAII_wrapper_type<UninitF> capture(InitF init_f, UninitF uninit_f, RType succ, 
                                   const char* error, Args... args)
{
  if(init_f(args...) != succ) {
    throw std::runtime_error(error);
  }
  return RAII_wrapper_type<UninitF>(uninit_f);
}

template<typename InitF, typename UninitF, typename... Args>
RAII_wrapper_type<UninitF> capture(InitF init_f, UninitF uninit_f, Args... args)
{
  init_f(args...);
  return RAII_wrapper_type<UninitF>(uninit_f);
}

例子:

void t_void_init(int){}
int t_int_init(){ return 1; }
void t_uninit(){}

int main()
{
  auto t1 = capture(t_void_init, t_uninit, 7);
  auto t2 = capture(t_int_init, t_uninit, 0, "some error");
}

编辑

RAII_wrapper_type应该有移动语义,我们应该小心地实现它的移动构造函数,以防止uninit_f多次调用。

于 2013-01-19T22:04:23.567 回答
3

我会分开返回检查和 RAII-Wrapping 的逻辑

template <typename UninitFuncType>
class RAIIWrapper
{
public:
  template <typename InitFuncType, typename... Args>
  RAIIWrapper(InitFuncType fpInitFunc,
              UninitFuncType fpUninitFunc,
              Args&&... args)
    : fpUninit(std::move(fpUninitFunc))
  {
    static_assert(std::is_void<decltype(fpInitFunc(args...))>::value, "ignored return value");
    fpInitFunc(std::forward<Args>(args)...);
  }

  bool isInitialized() const { return true; } // false is impossible in your implementation

  ~RAIIWrapper() { fpUninit(); } // won't be called if constructor throws

private:
  UninitFuncType fpUninit; // avoid overhead of std::function not needed
};

template <typename InitFuncType, typename UninitFuncType, typename... Args>
RAIIWrapper<UninitFuncType>
raiiWrapper(InitFuncType fpInitFunc,
            UninitFuncType fpUninitFunc,
            Args&&... args)
{
  return RAIIWrapper<typename std::decay<UninitFuncType>::type>
    (std::move(fpInitFunc), std::move(fpUninitFunc), std::forward<Args>(args)...);
}

template <typename InitFuncType, typename SuccessValueType>
struct ReturnChecker {
  InitFuncType func;
  SuccessValueType success;
  const char *errorString;
  ReturnChecker(InitFuncType func,
                SuccessValueType success,
                const char *errorString)
    : func(std::move(func)), success(std::move(success)), errorString(errorString) {}

  template <typename... Args>
  void operator()(Args&&... args)
  {
    if (func(std::forward<Args>(args)...) != success)
      throw std::runtime_error(errorString);
  }
};
template <typename InitFuncType, typename SuccessValueType,
          typename Ret = ReturnChecker<InitFuncType, SuccessValueType> >
Ret checkReturn(InitFuncType func, SuccessValueType success, const char *errorString)
{
  return Ret{func, success, errorString};
}

我还添加了允许类型推断的功能。以下是如何使用它:

auto _ = raiiWrapper(checkReturn(glfwInit, GL_TRUE, "Failed to initialize GLFW"),
                     glfwTerminate);

由于拥有一个具有非 void 返回值的函数对象会导致 static_assert 失败,因此以下情况是不可能的:

raiiWrapper(glfwInit, glfwTerminate); // fails compiling

如果你真的想忽略它,你可以添加一个ignoreReturn函数对象。另请注意,返回码检查可以根据需要进行复杂的操作(例如成功必须是偶数),因为您可以编写自己的返回码检查器。

于 2013-01-19T21:39:18.307 回答