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

前端 未结 4 555
北恋
北恋 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-16 13:13

    I'll just add a short clarification, because the answer was already given. resize() with argument greater than current size will add elements to the collection and default - initialize them. If You create

    std::vector v;
    

    and then resize

    v.resize(someSize);
    

    All unsigned chars will get initialized to 0. Btw You can do the same with a constructor

    std::vector v(someSize);
    

    So theoretically it may be a little bit slower than a raw array, but if the alternative is to copy the array anyway, it's better.

    Reserve only prepares the memory, so that there is no reallocation needed, if new elements are added to the collection, but You can't access that memory.

    You have to get an information about the number of element written to Your vector. The vector won't know anything about it.

提交回复
热议问题