简体   繁体   English

Autoregister对象列出存储共享指针

[英]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(). 在构造函数或单独的初始化函数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 我不想直接使用容器singleton的register / unregister方法,因为

  • 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 : 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());
    }
};

从std :: enable_shared_from_this派生你的对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM