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

时间:2012-01-10 07:07:04

标签: c++ shared-ptr smart-pointers tr1 reference-counting

为了引用计数,使用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;
};

1 个答案:

答案 0 :(得分:9)

请考虑使用带有自定义删除器的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;
};