Note that there are some explanatory texts on larger screens.

plurals
  1. POMemory mapped file class, threads and reference counting
    primarykey
    data
    text
    <p>I'm putting together a class I'm going to call a file.</p> <p>The file object simply contains a pointer to a memory mapped file and a link.</p> <p>The constructor takes a file and maps the file onto memory range. In summary it looks a bit like this:</p> <pre><code>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_; }; </code></pre> <p>Now, This file object can be copied around.</p> <p>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.</p> <p>What mechanisms can I use to decide when to delete the memory and munmap?</p> <p>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.</p> <p>i.e. </p> <pre><code>boost::shared_ptr&lt;unsigned char&gt; bytes_; ~file() { // enter some sort of critical section if (bytes_.unique()){ munmap(bytes_); bytes_ = 0; } // exit critical section } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload