Using std::vector as view on to raw memory

后端 未结 10 1593
感动是毒
感动是毒 2021-01-31 13:34

I\'m using a external library which at some point gives me a raw pointer to an array of integers and a size.

Now I\'d like to use std::vector to access and

10条回答
  •  失恋的感觉
    2021-01-31 13:41

    You actually could almost use std::vector for this, by abusing the custom allocator functionality to return a pointer to the memory you want to view. That wouldn't be guaranteed by the standard to work (padding, alignment, initialization of the returned values; you'd have to take pains when assigning the initial size, and for non-primitives you'd also need to hack up your constructors), but in practice I would expect it to given enough tweaks.

    Never ever ever do that. It's ugly, surprising, hacky, and unnecessary. The standard library's algorithms are already designed to work as well with raw arrays as with vectors. See the other answers for details of that.

提交回复
热议问题