Using read() directly into a C++ std:vector

前端 未结 4 562
北恋
北恋 2020-12-16 12:21

I\'m wrapping up user space linux socket functionality in some C++ for an embedded system (yes, this is probably reinventing the wheel again).

I want to offer a read

4条回答
  •  难免孤独
    2020-12-16 13:02

    Use resize() instead of reserve(). This will set the vector's size correctly -- and after that, &myvec[0] is, as usual, guaranteed to point to a continguous block of memory.

    Edit: Using &myvec[0] as a pointer to the underlying array for both reading and writing is safe and guaranteed to work by the C++ standard. Here's what Herb Sutter has to say:

    So why do people continually ask whether the elements of a std::vector (or std::array) are stored contiguously? The most likely reason is that they want to know if they can cough up pointers to the internals to share the data, either to read or to write, with other code that deals in C arrays. That’s a valid use, and one important enough to guarantee in the standard.

提交回复
热议问题