Memory mapped file storage in stl vector

前端 未结 3 2005
天涯浪人
天涯浪人 2021-01-13 07:46

I\'m trying to implement custom allocator for storing memory mapped files in the std::vector. Files mapping performed by boost::iostreams::ma

3条回答
  •  离开以前
    2021-01-13 08:26

    To make the advice from NetVipeC's answer explicit (with help from the mmap_allocator library suggested by Johannes Thoma), if you're using the GNU Standard C++ Library the following replacement for your mm_vector class prevents the contents of your memory-mapped vector from being initialized to zero (and eliminates the need for the GetFileSize function):

    template 
    class mm_vector : public std::vector> {
    public:
        typedef mmap_allocator allocator_type;
        typedef std::vector b_vector;
    
        mm_vector(const std::string filename)
            : b_vector(allocator_type(filename)) {
    
            allocator_type * a = &b_vector::_M_get_Tp_allocator();
            size_t n = a->size() / sizeof(T);
            b_vector::reserve(n);
            // _M_set_finish(n);
            this->_M_impl._M_finish = this->_M_impl._M_end_of_storage = this->_M_impl._M_start + n;
        }
    };
    

    We prevent the contents of the vector from being zeroed by allowing it to be initialized with the default size of 0, and then fiddle with its internals afterward to adjust the size. It's unlikely that this is a complete solution; I haven't checked whether operations that change the size of the vector work properly for example.

提交回复
热议问题