假设我有一个名为 Dog 的类。每只狗都有不同的名字,但叫声相同(从资源文件加载)。
class Dog {
public:
Dog(const string &name) : _name(name) {
_barkingVoice.load();
}
~Dog() {
_barkingVoice.free();
}
string getName() const { return _name; }
void bark() { _barkingVoice.play(); }
private:
string _name;
VoiceResource _barkingVoice;
};
只有当 Dog 的实例是第一个时,我才想调用 _barkingVoice.load()
,并且只有当没有更多实例时才调用 _barkingVoice.free()
狗的。
显而易见的解决方案是将 _barkingVoice 设置为静态并将 Dog 的引用计数器保留为数据成员。
我的问题是是否有更简单的方法来做到这一点。也许是标准实现或类似的东西。
最佳答案
制作一个可重用的类来封装引用计数:
template<class ResourceType, class OwnerType>
class RefCounted {
public:
RefCounted() { if (++_refCount == 1) _resource.load(); }
virtual ~RefCounted() { if (--_refCount == 0) _resource.free(); }
ResourceType& operator*() { return _resource; }
ResourceType* operator->() { return &_resource; }
private:
static unsigned _refCount;
static ResourceType _resource;
};
template<class T, class U> unsigned RefCounted<T, U>::_refCount = 0;
template<class T, class U> T RefCounted<T, U>::_resource;
class Dog {
public:
Dog(const string &name) : _name(name) { }
string getName() const { return _name; }
void bark() { _barkingVoice->play(); }
private:
string _name;
RefCounted<VoiceResource, Dog> _barkingVoice;
};
每个模板实例都有自己的_refCount
和 _resource
.
第二个模板参数用于处理实例化 RefCounted
的情况与相同ResourceType
但希望对这些实例进行单独的引用计数。例如。如果你添加 Cat
类并希望它有自己的 Refcounted<VoiceResource>
:
class Cat {
// ...
private:
RefCounted<VoiceResource, Cat> _meowingVoice;
};
关于c++ - 对象的共享资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33581264/