4

Is it legal to directly copy data into 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);
Mansoor
  • 2,357
  • 1
  • 17
  • 27
Dess
  • 2,064
  • 19
  • 35
  • 5
    Fine with a simple [POD type](https://stackoverflow.com/questions/146452/what-are-pod-types-in-c) like `char`. Don't try it with, for example, a `std::vector`. Side note: Worth seeing if you can `FillBuff(vbuf.data());` and skip the `memcpy` entirely. – user4581301 Oct 10 '20 at 22:23
  • 1
    Note also that `memcpy(vbuf.data(), &buf, 255);` has an unneeded `&`; just `memcpy(vbuf.data(), buf, 255);` will do. – Adrian Mole Oct 10 '20 at 22:24
  • 2
    Yes but why, just use `std::copy` – Mansoor Oct 10 '20 at 22:25
  • @M.A It may be required, for example, to pass the `vbuf.data()` pointer to a function (maybe written in plain ol' C) that takes a `char*` argument. – Adrian Mole Oct 10 '20 at 22:27
  • 3
    Yes, it ok, but use `std::copy(std::begin(buf), std::end(buf), vbuf.begin());` - The assembly will most probably be the same but it makes for easier maintenance. – Ted Lyngmo Oct 10 '20 at 22:28

1 Answers1

3

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.

Mansoor
  • 2,357
  • 1
  • 17
  • 27