Recycling objects with various types (inheritance)

Status
Not open for further replies.

puffinus

Ars Praefectus
4,381
Subscriptor
This should be an easy question but I think I don't know what the right keywords are to search by.

What's the best way in C++ to implement object recycling when the consumer/user of instances only knows them by a generic interface?

Example:

Class CTargetOfActions (holds state)

Pure virtual class CWidget, exposes function DoStuff(CTargetOfActions &Target)

Classes which implement/inherit from CWidget:
CRedWidget
CBlueWidget
CYellowWidget

The user of these classes gets them from a class factory which uses criteria the user doesn't understand to pick which one(s) to use and initialize them, then supply them as a vector of CWidget pointers.

So, what's the best way for the user to hand them back to the class factory for reuse when the consumer doesn't know exactly which type they are? Should CWidget have a member/property exposed revealing what type it is and the class factory a single Recycle(CWidget) call?
 
Should CWidget have a member/property exposed revealing what type it is
You already know what type it is (typeid, dynamic_cast).

and the class factory a single Recycle(CWidget) call?
Possibly. You might even be able to plumb it into the class's operator delete. I should know for sure (I'm fuzzy about the interactions between operator delete overrides, memory deallocation, and destructor calling) but alas I do not. It's not an area I've poked much.
 

puffinus

Ars Praefectus
4,381
Subscriptor
DrPizza":2uyp9t6a said:
Should CWidget have a member/property exposed revealing what type it is
You already know what type it is (typeid, dynamic_cast).

and the class factory a single Recycle(CWidget) call?
Possibly. You might even be able to plumb it into the class's operator delete. I should know for sure (I'm fuzzy about the interactions between operator delete overrides, memory deallocation, and destructor calling) but alas I do not. It's not an area I've poked much.

Thanks.

I wasn't sure about the costs of typeid and dynamic_cast since I don't know of a way to get them to an integer I can use in an efficient switch statement or similar structure. The objects I'm looking at are very lightweight and there are potentially a hundred or so different types. The real CWidget is pretty close to alternatives in an alpha-beta search across a tree where an agent supplies the best alternatives for a given position and what's going on inside the CWidget that makes it manipulate the world state is quite opaque to the code running the tree. There are consequently lots of create/inits and lots of recycling going on.
 

LordHunter317

Ars Legatus Legionis
22,394
Subscriptor
One totally alternative approach, assuming all the subclass of CWidget are known at compile time, would be to use a boost::variant. It does break the intent that the class user isn't supposed to known the underlying type, though.

Otherwise, the simplest approach seems to be to store the objects when you create them, negating the need for Recycle to do anything altogether[1]. This makes type identification an implementation detail for the factory class. There, you have three options:
  • Use typeid. C++11 provides a std::type_index structure that wraps std::type_info and can be used as a map keys. C++98 does not, so you'll have to recreate it manually. I believe that's possible but I don't know how hard it would be.
  • If all the types are known, just assign integers (or whatever key you'd like) to each type internally and make Recycle a no-op.
  • Create a custom key for each type and store it as part of each CWidget object. This could be as simple as:
    Code:
    struct CWidget {
         virtual void DoStuff(...) = 0;
         virtual int getType() = 0;
         virtual ~CWidget() {}
    }
    
    // Repeat for each class.
    struct CRedWidget : public CWidget {
        static int Type = 12345;  // I've got the same combination on my luggage.
        virtual int getType() { return Type; } 
    }
    Obviously, you can modify that to ensure uniqueness in various ways.

[1] Recycle need not even exist, and I'm not 100% sure it should. I would just return a smart pointer of some sort, instead of bare pointers, and hook any cleanup/cache/whatever logic that way.
 

puffinus

Ars Praefectus
4,381
Subscriptor
LordHunter317":1u02piwg said:
One totally alternative approach, assuming all the subclass of CWidget are known at compile time, would be to use a boost::variant. It does break the intent that the class user isn't supposed to known the underlying type, though.

I'll look at that. I'm not as familiar with boost as I should be.

Otherwise, the simplest approach seems to be to store the objects when you create them, negating the need for Recycle to do anything altogether[1].

Maybe I don't understand what you're saying. I'd still need to keep track of which ones are in use versus available for reuse.

This makes type identification an implementation detail for the factory class. There, you have three options:
  • Use typeid. C++11 provides a std::type_index structure that wraps std::type_info and can be used as a map keys. C++98 does not, so you'll have to recreate it manually.


  • Doable, I can use pretty much any compiler I want.

    If all the types are known, just assign integers (or whatever key you'd like) to each type internally and make Recycle a no-op.[*]Create a custom key for each type and store it as part of each CWidget object. This could be as simple as:
    Code:
    struct CWidget {
         virtual void DoStuff(...) = 0;
         virtual int getType() = 0;
         virtual ~CWidget() {}
    }
    
    // Repeat for each class.
    struct CRedWidget : public CWidget {
        static int Type = 12345;  // I've got the same combination on my luggage.
        virtual int getType() { return Type; } 
    }
    Obviously, you can modify that to ensure uniqueness in various ways.

If I'm adding a static member to each instance, is there a reason to tag with a type index rather than just adding a static reference to the class factory to each type and then to the CWidget
virtual void CWidget::Recycle() = 0;

and to each type
void CRedWidget::Recycle() {
m_classFactory->RecycleRedWidget(this);
}
etc.
?
 

LordHunter317

Ars Legatus Legionis
22,394
Subscriptor
puffinus":12ion0nt said:
Otherwise, the simplest approach seems to be to store the objects when you create them, negating the need for Recycle to do anything altogether[1].
Maybe I don't understand what you're saying. I'd still need to keep track of which ones are in use versus available for reuse.
Sure. You can accomplish this by giving a shared_ptr a "deleter", a custom functor that is called to delete the underlying storage. They're useful if the shared_ptr is protecting a resource not allocated by new/delete.

So just write a custom deleter that signals to the factory the object is available for reuse. Note that deleters basically aren't allowed to throw exceptions, and must be CopyConstructable and Assignable, so make sure that the factory always has a valid pointer to the underlying object, and the deleter always has a valid pointer to the factory.

Roughly, something like:
Code:
class RecycleWidget {
    Factory* factory; // This can actually be a shared_ptr too.
public:
    void operator()(CWidget* ptr) {  factory->Release(ptr); }
}

// Partial
class Factory  {
     // Holds instances, used or not.  When returning a new instance, fetch it from here and
     // check for it in the used set before returning it.
     std::map<std::type_index, std::vector<CWidget*> > instances; 
     std::set<CWidget*> used; // Holds instances in use.
public:
     void Release(CWidget* ptr) {
          used.erase(ptr);
     }
as one possible approach of many. You can also just add a flag to the CWidget class, but then I would make the deleter a friend so other users can't modify the flag.

If I'm adding a static member to each instance, is there a reason to tag with a type index rather than just adding a static reference to the class factory to each type and then to the CWidget
virtual void CWidget::Recycle() = 0;

and to each type
void CRedWidget::Recycle() {
m_classFactory->RecycleRedWidget(this);
}
etc.
?
This approach is fine too, assuming you're OK with the only being able to create widgets inside the factory. You may be able to use a template method to avoid creating a unique Recycle function for every type.
 

puffinus

Ars Praefectus
4,381
Subscriptor
Thanks guys!

For now, I'm going to go with adding a pure virtual Recycle function to the CWidget class which in each instance calls a type-specific recycling function on the class factory because:
1) should be widely compatible without any library dependencies (even boost/etc.)
2) reasonably fast with clear code flow
3) direct calls, without mapping lookups or something similar to index by TypeId or equivalent
4) Leaves my options open as far as where the objects are stored (stack or heap) because it doesn't rely on delete or destructor behavior so I'm free to experiment for best performance if that becomes necessary.

All of the individual classes (CRedWidget etc.) are going to be automatically generated anyway so I don't think I gain anything from templates.

My homework assignment is to look at delete/destructors to see what's allowed for repurposing them and to check out shared_ptr and the new typeid extension in C++11.

Thanks again!
 
Status
Not open for further replies.