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;
};
Consider instead using a
shared_ptr<FILE>
with a custom deleter:Then, your
File
class is much simpler (and correcter):