vendredi 11 juin 2021

C++ handle class abstraction

I am trying to abstract the explicit creation and destruction of raw handles with the usage of classes. The actual handle is stored as a private class member (so that the user doesn't interact with the lower-level details), which is created on construction and destroyed on destruction. Is there a design pattern of some sorts that could help achieve what the code below is trying to accomplish?

Note that it is possible for there to be loads of classes interdependent to each other, therefore it would be both tedious and bad practice to pollute each class with lots of friend statements.

#include <memory>

// Handle types may vary
typedef uint32_t A_Handle;
typedef uint32_t B_Handle;
typedef int64_t C_Handle;

extern void createA(A_Handle*);
extern void destroyA(A_Handle);
extern void createB(B_Handle*);
extern void destroyB(B_Handle);
extern void createC(C_Handle*, A_Handle, B_Handle);
extern void destroyC(C_Handle, A_Handle, B_Handle);

class A
{
private:
    A_Handle handle_;
public:
    A()
    {
        createA(&handle_);
    }

    ~A()
    {
        destroyA(handle_);
    }
};

class B
{
private:
    B_Handle handle_;
public:
    B()
    {
        createB(&handle_);
    }

    ~B()
    {
        destroyB(handle_);
    }
};

class C
{
private:
    C_Handle handle_;
public:
    std::shared_ptr<A> a;
    std::shared_ptr<B> b;

    C(const std::shared_ptr<A>& a, const std::shared_ptr<B>& b)
        : a(a)
        , b(b)
    {
        // Error a->handle_ and b->handle_ is private
        createC(&handle_, a->handle_, b->handle_);
    }

    ~C()
    {
        // Error a->handle_ and b->handle_ is private
        destroyC(handle_, a->handle_, b->handle_);
    }
};

// ...

int main()
{
    std::shared_ptr<A> a = std::make_shared<A>();
    std::shared_ptr<B> b = std::make_shared<B>();
    std::shared_ptr<C> c = std::make_shared<C>(a, b);

    // ...

    return EXIT_SUCCESS;
}

Aucun commentaire:

Enregistrer un commentaire