【发布时间】:2011-11-30 17:38:38
【问题描述】:
我观察到在我的程序中,我需要让几个类使用以下通用模式。它背后的想法是resource_mgr 维护一个指向resource 对象的引用计数指针列表,并专门控制它们的生命周期。客户端不能创建或删除resource 实例,但可以从resource_mgr 请求它们。
class resource_impl
{
public:
// ...
private:
resource_impl(...);
~resource_impl();
// ...
friend class resource_mgr;
}
class resource_mgr
{
public:
// ...
shared_ptr<resource_impl> new_resource(...);
private:
std::vector<shared_ptr<resource_impl> > resources_;
static void delete_resource(resource* p); // for shared_ptr
}
我如何(或者我可以?)定义一个模板来捕捉这种常见行为? 以下说明了如何使用此模板:
class texture_data
{
// texture-specific stuff
}
typedef resource_impl<texture_data> texture_impl;
// this makes texture_impl have private *tors and friend resource_mgr<texture_impl>
typedef resource_mgr<texture_impl> texture_mgr;
//...
texture_mgr tmgr;
shared_ptr<texture_impl> texture = tmgr.new_resource(...);
更新:resource_impl 的各种实例化都应具有以下共同属性:
- 他们有私有的构造函数和析构函数
- 他们的“关联”
resource_mgr(管理相同类型资源的管理器类)是一个朋友类(因此它可以创建/销毁实例)
【问题讨论】:
-
什么常见的行为? resource_imp 的?
-
resource_impl和resource_mgr。 -
resource是如何发挥作用的? -
resource只是我使用的 typedef。我将从问题中删除它以使事情更清楚。 -
您能否展示几个将使用此共享功能的对象的示例或伪代码,以及说明您希望如何使用它的伪代码?