Search code examples
c++filestreamreinterpret-castcontiguous

How to check whether iterators form a contiguous memory zone?


I currently have the following function to read an array or a vector of raw data (_readStream is a std::ifstream) :

template<typename IteratorType> 
inline bool MyClass::readRawData(
    const IteratorType& first, 
    const IteratorType& last, 
    typename std::iterator_traits<IteratorType>::iterator_category* = nullptr
    )
{
    _readStream.read(reinterpret_cast<char*>(&*first), (last-first)*sizeof(*first));
    return _readStream.good();
}

First question : does this function seem ok for you ?

As we read directly a block of memory, it will only work if the memory block from first to last is contiguous in memory. How to check that ?


Solution

  • Leaving aside your sample function, you can never be completely sure that iterators will form a contiguous memory without checking the address of every element between the two.

    A reasonable sanity test, though, would be to just check if the memory area between the two is the same as the count between the two:

    assert(&*last - &*first == last - first &&
        "Iterators must represent a contiguous memory region");