Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memcpy data directly into std::vector

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);
like image 208
Dess Avatar asked Sep 06 '25 03:09

Dess


1 Answers

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.

like image 169
Mansoor Avatar answered Sep 08 '25 00:09

Mansoor