我想要做的是编写一个小的 Manager/Handler 类。管理器分发和管理句柄。例如,这样的句柄可以是简单的文件句柄。
如果消费者想要获取已经存在的句柄,管理器只需返回一个 shared_ptr。如果句柄不存在,则管理器创建一个新句柄,然后返回 shared_ptr。
在 Manager 内部,那些 shared_ptr 存储在一个简单的 STL-Map 中。如果分配的最后一个 shared_ptr 被删除,我希望我的经理删除相关的地图元素,以便处理程序对象自动被破坏。
这听起来有点像垃圾收集(例如工作线程,它检查指针的使用计数),但我相信它可以做得更优雅。
如何将管理器实例的引用传递给处理程序对象?(例如,就像将 unique_ptr(this) 传递给新处理程序的构造函数)
#include <memory>
#include <iostream>
#include <map>
using namespace std;
/*
* Simple handler class, that actually does nothing.
* This could be e.g. a Filehandler class or sth. like that
*/
class Handler {
private:
int i;
public:
Handler(int i) :i(i) {}
~Handler() {}
// Say who you are.
void print(void) { cout << "I am handler # " << i << endl; }
};
/*
* This is the "manager" class, that manages all handles. A handle is identified
* by an integer value. If a handle already exists, the Manager returns a shared_ptr,
* if it does not exist, the manager creates a new handle.
*/
class Manager {
private:
map<int, shared_ptr<Handler> > handles;
public:
Manager() {}
~Manager() {}
shared_ptr<Handler> get_handler(int identifier) {
shared_ptr<Handler> retval;
auto it = handles.find(identifier);
if(it != handles.end() ) {
retval = it->second;
} else {
retval = shared_ptr<Handler>(new Handler(identifier));
handles.insert( pair<int, shared_ptr<Handler>>(identifier, retval) );
}
return retval;
}
};
int main(int argc, char** argv) {
Manager m;
// Handler 13 doesn't exist, so it gets allocated
auto h = m.get_handler(13);
// Manager knows about handler 13, so it returns the already existing shared_ptr
auto i = m.get_handler(13);
h.reset(); // Well... Let's assume we don't need h any more...
// do some stuff...
i->print();
// ...
i.reset(); // We also loose i. This is exactly the point where i want the manager to forget about the handle 13
return 0;
}