在 C++ 中为 C 样式对象创建透明包装器 class

Create a transparent wrapper class in C++ for a C-style object

我想在 C++ 中实现一个 class,其目的是为 C 风格对象实现 RAII 机制。

然后,我需要能够将此 class 的实例传递给所有接收上述 C 样式对象作为参数的 C 样式函数。我知道这应该用 unique_ptr 来解决,但我现在不能使用 C++11。不管怎样,我想知道这个应该怎么做,不管有没有更好的解决方案。

关于必须重载哪些运算符,以及其中一些运算符之间的区别,我有几个疑问。

下面是我实现的代码示例。我特别混淆运算符1和2(有什么区别?)

我想知道我实现的代码是否涵盖所有用例,我的意思是,C 库可以使用该对象的所有场景。另外,想了解运算符1和2的区别

C 风格对象

// Example: a C-style library called "clib" which use an object called "cobj":

struct cobj {
    int n;    
};

void clib_create_cobj(struct cobj **obj) {
    *obj = (struct cobj*)malloc(sizeof(cobj));
    (*obj)->n = 25;
}

void clib_release_cobj(struct cobj *obj) {
    free(obj);
}

void clib_doSomething(struct cobj *obj) {
    std::cout << obj->n << std::endl;
}

C++ "transparent" 包装器

// My wrapper class for implementing RAII

class CobjWrapper {
    public:
        CobjWrapper(struct cobj *obj) : m_obj (obj) { }

        ~CobjWrapper() {
            if(m_obj != NULL) {
                clib_release_cobj(m_obj);
                m_obj = NULL;
            }
        }


        operator struct cobj* () const {    // (1)
            return m_obj;
        }

        struct cobj& operator * () {        // (2)
            return *m_obj;
        }

        struct cobj** operator & () {       // (3)
            return &m_obj;
        }

        struct cobj* operator->() {     // (4)
            return m_obj;
        }

    private:
        struct cobj *m_obj;

};

主要方法

// The main method:

int main() {
  struct cobj *obj = NULL;

  clib_create_cobj(&obj);

  CobjWrapper w(obj);
  clib_doSomething(w);

  return 0;
}

上面的源码可以在这里测试:

http://cpp.sh/8nue3

下面是一个隐式转换

operator struct cobj* () const {    // (1)

使用示例

CobjWrapper wrapper = /**/;

struct cobj* obj = wrapper;

而下面是一元operator *

struct cobj& operator * () {        // (2)

使用示例

CobjWrapper wrapper = /**/;

struct cobj& obj = *wrapper;

顺便说一句,我会完全隐藏 C 结构,例如:

class CobjWrapper {

    struct ObjDeleter
    {
        void operator()(cobj *obj) const { clib_release_cobj(obj); }
    };

    public:
        CobjWrapper()
        {
             cobj *obj = nullptr;
             clib_create_cobj(&obj);
             m_obj.reset(obj);
        }

        void doSomething() { clib_doSomething(m_obj.get()); }

    private:
        std::unique_ptr<cobj, ObjDeleter> m_obj;
};