c++ - Autoregister Objects to list stores shared pointers -
i implement base object, can autoregister singleton object list. store shared pointers pointing these objects in list. registration happen either in constructor or separate initialisation function set(). problem object not know it's shared pointer. how can solve problem?
the object:
class object { public: object() {} virtual ~object() {} void set() { // register object, how? } void unset() { // unregister object, how? } };
the object list:
#include <memory> #include <list> class objectpool { public: void unregisterobject(std::shared_ptr<object> objptr) { objptrlist.remove(objptr); } void registerobject(std::shared_ptr<object> objptr) { objptrlist.push_back(objptr); } private: std::list<std::shared_ptr<object> > objptrlist; };
usage:
int main() { auto objptr = std::make_shared<object>(); objptr->set(); objptr->unset(); }
i not want use register/unregister methods of container singleton directly, because
- i want hide registering mechanism user codes, and
- set/unset functions additional staff besides registering
i suspect problem may come inadequate design i'm interested in solutions different designs also, if can used same purpose.
update: solution
deriving object std::enable_shared_from_this:
class object : public std::enable_shared_from_this<object> { public: object() {} virtual ~object() {} void set() { objectpool.registerobject(shared_from_this()); } void unset() { objectpool.unregisterobject(shared_from_this()); } };
derive object std::enable_shared_from_this.
Comments
Post a Comment