Is it legal to directly copy data into the underlying buffer of a std::vector using memcpy? Something like this:
char buf[255];
FillBuff(buf);
std::vector<char> vbuf;
vbuf.resize(255);
memcpy(vbuf.data(), &buf, 255);
To answer your question yes, it does work but that is due to the implementation of std::vector<char>
.
For non-POD types and types for which std::vector
has a particular template specialisation that affects the memory layout (std::vector<bool>
), it will not work. This is why you should use std::copy
, it will behave correctly irrespective.
As noted by @user4581301, memcpy
may be unnecessary as you can treat std::vector:: data()
as you do the char* buffer
.