3

出于引用计数的目的,在下面的示例代码中使用 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;
};
4

1 回答 1

9

考虑改为使用shared_ptr<FILE>带有自定义删除器的 a :

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;
};
于 2012-01-10T07:13:06.693 回答