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

标签 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;
};

最佳答案

考虑改用 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;
};

关于c++ - 使用 std::tr1::shared_ptr 作为引用计数的内部机制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8799735/

相关文章:

c++ - 创建自定义 end() 迭代器

c++ - shared_ptr 分配 : order of reference counting

multithreading - 为什么boost::shared_ptr在不是线程安全的情况下会麻烦原子引用计数?

smart-pointers - 正确使用 std::shared_ptr 和 std::auto_ptr

c++ - 何时使用 unique_ptr 而不是本地对象?

class - 智能指针和析构函数

c++ - Github 通过克隆获得必要的库

c++ - 单击鼠标时不需要的 SDL_QUIT 事件

c++ - Qt5.5静态构建在ubuntu14上找不到-IGL

c++ - 使用 boost 正则表达式时出现 shared_ptr 错误