Combining an array of C objects into a C ++ class

I have a library Cwith this API:

extern "C" {
    typedef struct Opaque Opaque;

    Opaque *foo_new();
    void foo_delete(Opaque *);
    int foo_f(Opaque *, int);
}

To make it easier to use, I wrap it this way:

class Foo final {
public:
    Foo() { self_ = foo_new(); }
    ~Foo() { foo_delete(self_); }
    //code for copy/move constructor and operator=
    int f(int a) { return foo_f(self_, a); }
private:
    Opaque *self_;
};

Everything is fine, but then I need to wrap an array of these opaque objects:

extern "C" {
    typedef struct OpaqueArray OpaqueArray;

    OpaqueArray *calc_foo_array();
    void foo_array_delete(OpaqueArray *);
    Opaque *foo_array_elem(OpaqueArray *, size_t i);
}

Therefore, I need to implement class FooArray:

class FooArray final {
public:
    ??? operator[](const size_t i) {
       auto obj = foo_array_elem(self_, i);
       ???
    }
private:
    OpaqueArray *self_;
};

But what should I return as a result operator[]?

Foo Opaque *, Foo::~Foo() , . FooRef, , Foo, foo_delete, C classes, . , - reinterpret_cast - sizeof(Foo) = sizeof(Opaque *) Foo & operator[], Foo & Opaque **, - Opaque, .

, - ?

+4
2

, FooRef, :

class FooRef {
public:
    FooRef (Opaque *o) { self_ = o; }
    int f(int a) { return foo_f(self_, a); }
protected:
    Opaque *self_;
};


class Foo : public FooRef {
public:
    Foo() { self_ = foo_new(); }
    //code for copy/move constructor and operator=
    ~Foo () { foo_delete(self_); }
};

Foo . , , FooRef Foo. :

class FooArray final {
public:
    FooRef operator[](const size_t i) {
       return FooRef(foo_array_elem(self_, i));
    }
private:
    OpaqueArray *self_;
};

, .

+2

Foo, , .

class Foo
{
    public:
        Foo()
        {
            self_ = foo_new();
            m_owned = true;
        }

        Foo(Opaque *pOpaque) 
        { 
            self_ = foo_new(); 
            m_owned = false;
        }

        ~Foo()
        {
            if (m_owned) foo_delete(self_);
        }

        //code for copy/move constructor and operator=
        int f(int a) { return foo_f(self_, a); }

    private:
        bool m_owned;
        Opaque *self_;
};


class FooArray
{
    public:
        Foo operator[](const size_t i)
        {
           return Foo(foo_array_elem(self_, i));
        }

    private:
        OpaqueArray *self_;
};
+4

Source: https://habr.com/ru/post/1693124/


All Articles