使用std::tr1::sharedptr作为引用计数的内部机制



在下面的示例代码中使用std::tr1::shared_ptr进行引用计数是否安全正确?(这只是一个特定的示例,类可以包含任何其他内容(void*)而不是FILE*)

class File
{
public:
    File(const char* path, const char* mode) :
        _refcount(new int(0))
    {
        this->_file = fopen(path, mode);
    }
    ~File()
    {
        if (this->_refcount.unique())
        {
            if (this->_file != NULL)
            {
                fclose(this->_file);
            }
        }
    }
    int write(void* buff, size_t size)
    {
        fwrite(buff, size, 1, this->_file);
    }
private:
    FILE* _file;
    std::tr1::shared_ptr<int> _refcount;
};

考虑使用带有自定义deleter的shared_ptr<FILE>

struct fclose_deleter
{
    void operator()(FILE* f)
    {
        if (f)
        {
            std::fclose(f);
        }
    }
};

然后,您的File类要简单得多(而且是正确的):

class File
{
public:
    File(const char* path, const char* mode)
        : _file(std::fopen(path, mode), fclose_deleter())
    {
    }
    int write(void const* buff, size_t size)
    {
        // You'll want to verify that _file.get() is valid, or you'll want to
        // throw in the constructor if the call to 'std::fopen()' fails.
        std::fwrite(buff, size, 1, _file.get());
    }
private:
    std::tr1::shared_ptr<FILE> _file;
};

相关内容

  • 没有找到相关文章

最新更新