Question

I am creating a Lua api for my program. I want to be able to do the following:

void* CreateA()
{
     A* a = new A();
     PointerTypes[a] = A;
     return reinterpret_cast<void*>(a);
}

void* CreateB()
{
     B* b = new B();
     PointerTypes[b] = B;
     return reinterpret_cast<void*(b);
}

void DeleteThing( void* p )
{
     typename type = PointerTypes[p];
     type* t = reinterpret_cast< type >( p );
     delete t;
}

Is there any straightforward way to do this? PS: My application already uses RTTI so it can be used here too.

Was it helpful?

Solution

Instead of saving the type in a map (which is not possible because types aren't first class objects in C++) you could store a deleter function in a map. Your factory function then becomes:

void* CreateA()
{
    A *a = new A();
    PointerDeleters[a] = [](void *obj) { delete static_cast<A*>(obj); };
    return a;
}

or with a function template:

template<typename T>
void* Create() // maybe you want to forward c'tor args using variadic template
{
    T *a = new T();
    PointerDeleters[t] = [](void *obj) { delete static_cast<T*>(obj); };
    return t;
}

And then invoke it to trigger the deletion of the object p with unknown type:

void DeleteThing(void* p)
{
    PointerDeleters[p]();
}

The map PointerDeleters should then have the value type std::function<void(void*)>.

A better solution would be (if your design allows it) to use a base class with a virtual destructor; then you can simply delete a pointer to that class without storing any additional information:

template<typename T>
BaseClass* Create()
{
    return new T();
}

void DeleteThing(BaseClass* p)
{
    delete p;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top