c++ - 对象的共享资源

标签 c++

假设我有一个名为 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/

相关文章:

c++ - 如何在头文件中声明相同类类型的数组?

c++ - 为什么 gcc 生成一个 memmove 而不是 memcpy 来复制 std::vector<>?

C++ Eclipse Galileo 让它显示行号 - 怎么样?

c++ - 声明 ‘wxDECLARE_EVENT_TABLE’ 时出错

c++ - gets() 未在范围内声明

c++ - 为什么此代码会导致访问错误?

c++ - boost::spirit::qi 奇怪的属性打印出来

c++ - yaml-cpp 解析嵌套映射和序列错误

c++ - 在 Visual Studio 2010 中链接 libavformat

C++ 无效赋值