How can I access the contiguous memory buffer used within a std::vector so I can perform direct memory operations on it (e.g. memcpy)? Also, it is safe to perform operations like memcpy on that buffer?
I’ve read that the standard guarantees that a vector uses a contiguous memory buffer internally, but that it is not necessarily implemented as a dynamic array. I figure given that it is definitely contiguous, I should be able to use it as such – but I wasn’t sure if the vector implementation stored book-keeping data as part of that buffer. If it did, then something like memcpying the vector buffer would destroy its internal state.
In practice, virtually all compilers implement
vectoras an array under the hood. You can get a pointer to this array by doing&somevector[0]. If the contents of the vector are POD (‘plain-old-data’) types, doingmemcpyshould be safe – however if they’re C++ classes with complex initialization logic, you’d be safer using std::copy.