为了引用计数的目的,像下面的示例代码一样使用 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/