Search code examples
c++c++11shared-ptr

Autoregister Objects to list stores shared pointers


I would like to implement a base object, which can autoregister itself into a singleton object list. I would store shared pointers pointing to these objects in the list. The registration would be good to happen either in the constructor or a separate initialisation function set(). My problem is that the object does not know it's shared pointer. How can I solve this 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 would not want to use the register/unregister methods of the container singleton directly, because

  • I want to hide this registering mechanism from user codes, and
  • set/unset functions do additional staff besides registering

I suspect that this problem may come from inadequate design so I'm interested in solutions with completely different designs also, if they can used for the same purpose.

Update: Solution

Deriving Object from 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());
    }
};

Solution

  • Derive you Object from std::enable_shared_from_this.