jack
jack

Reputation: 576

Retrieving just the type of an object

I am using OGRE and I have run into an issue that is not so much specific to ORGE, but is a genreal C++ issue I am dealing with. ORGE just helps with the context of the question.

There is a macro that is something such as

OGRE_DELETE_T(obj, ExternalClass);

However, in order for delete to be called, I need to pass in the type of the class as the second parameter. However, say for instance I have a base class A, then class B, class C, class D, etc. If I were to store a std::vector of just A pointers, but in actuality I may have instantiated them as B, C, or some deriviative of A, how could I pass the type of the actual class constructed into this macro? I do not know what type the derived object is when I go to delete it, all I know is there is class A pointers.

I thought perhaps using dynamic_cast, however, I did not like the runtime performance and I would also need to have some sort of a lookup table of types to check against.

Upvotes: 0

Views: 81

Answers (2)

blueiso
blueiso

Reputation: 51

I know this question is old, but this answer might help others.

This macro is used to track your memory and if you need to use it on your derived types, you will have to compromise the interface a bit. One way you could do it is to create a virtual function that deletes the object appropriately. You do have to call specific destruction macro anyways when using OGRE_ALLOC_T or OGRE_NEW_T so the user could be aware of this special case.

class Parent
{
public:
    virtual void deleteSelf() = 0;
};

class A : public Parent
{
public:
    virtual void deleteSelf()
    {
        A* p = this;
        OGRE_DELETE_T(p, A);
    }
};

This way you can delete it this way:

Parent* p = OGRE_NEW_T(A);
p->deleteSelf();

Upvotes: 0

Tony The Lion
Tony The Lion

Reputation: 63200

Just pass the type of the derived object in the macro. It will delete your pointer properly, if your base has a virtual destructor.

Upvotes: 2

Related Questions