I'm putting together a class I'm going to call a file.
The file object simply contains a pointer to a memory mapped file and a link.
The constructor takes a file and maps the file onto memory range. In summary it looks a bit like this:
class file
{
public:
file(unsigned char* filename) { open(filename); }
open(unsigned char* filename)
{
/// snip
length_ = fstat(.....)
file_ = mmap(.....)
}
private:
unsigned int length_;
unsigned char* bytes_;
};
Now, This file object can be copied around.
Here comes the fun. Normally, a class like this would require a deep copy constructor to copy bytes_. However, I'm satisfied that I can just copy the pointer because the memory is shared and it should look at the same file anyway. I don't want to remap the file. But, obviously, to prevent a memory leak bytes_ at some point would need to be freed.
What mechanisms can I use to decide when to delete the memory and munmap?
I was thinking about using a boost::shared_ptr in order to free memory in the destructor only when it's the last reference, but I'd have to guard that with a mutex lock right? Are there some convenient boost functions for me to use already? I do not want to have to pull in another big library, it's not an option.
i.e.
boost::shared_ptr<unsigned char> bytes_;
~file()
{
// enter some sort of critical section
if (bytes_.unique()){
munmap(bytes_);
bytes_ = 0;
}
// exit critical section
}