Manage mapped memory (glMapBuffer) with std::vecto

2019-02-25 16:14发布

问题:

it occurred to me that it would be a good idea to manage a range of mapped memory (from glMapBuffer) with a std::vector.

// map data to ptr
T* dataPtr = (T*)glMapBuffer(this->target, access);

[... debug code ...]

// try to construct a std::vector from dataPtr
T* dataPtrLast = dataPtr + size;
mappedVector = new std::vector<T>(dataPtr, dataPtrLast);

the problem is that the memory range won't be used directly but it is copied into the vector.

My question would be: is it possible to make the vector just 'use' the mapped memory range. (and ideally throw exceptions on resize/reserve) Or is there any other standard container that would accomplish this?

Kind Regards, Florian

回答1:

No, and for good reason. This code would never work. For example, you could alter the MapBuffer and break the size/capacity values inside the vector. You could push into the vector and cause an access violation/segmentation fault. You could cause a resize, destroying the buffer. And, fundamentally, if it's already within a contiguous array, what's the benefit? You could roll a custom container for fixed length arrays, I guess.

Especially! if you already have a pair of pointers to act like iterators.