使用 std::tr1::shared_ptr 作为引用计数的内部机制
为了引用计数的目的,使用 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
考虑使用带有自定义删除器的
shared_ptr
:然后,您的
File
类会更简单(并且更正确):Consider instead using a
shared_ptr<FILE>
with a custom deleter:Then, your
File
class is much simpler (and correcter):