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

发布于 2024-12-25 14:56:33 字数 654 浏览 5 评论 0原文

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

Is it safe and correct to use an std::tr1::shared_ptr as in the sample code below, for the purpose of reference counting? (this is just a particular sample, the class can contain anything else (void*) instead of the 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;
};

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

冰魂雪魄 2025-01-01 14:56:33

考虑使用带有自定义删除器的 shared_ptr

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

Consider instead using a shared_ptr<FILE> with a custom deleter:

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

Then, your File class is much simpler (and correcter):

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;
};
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文