std::vector<unsigned char>
or std::vector<char>
are the obvious candidates (depending on the context), and indeed, most example code uses them:
https://stackoverflow.com/a/18816228/4442671
However, since std::vector
must construct all objects, you end up doing an extraneous memset()
, when compared to a simple dynamic allocation: https://godbolt.org/g/TKkwmp
It's not exactly a big deal, but it remains extra O(N) work that gets performed for no reason, so it feels like a break from the "don't pay for it if you don't need it" principle.
Writing a complete RAII wrapper around new[]
is not hard, but I can't help but wonder:
Is there a way to get a dynamic container of contiguous uninitialized memory out of the STL, or am I stuck reinventing that wheel?
Edit: I'm really confused by @Someprogrammerdude's reserve()
suggestion getting so many votes. Can someone please explain how dereferencing the reserved memory of a 0-sized vector is not a terrible idea?