Is it good practice to use std::vector as a simple buffer?
- Sure, this'll work fine. The one thing you need to worry about is ensuring that the buffer is correctly aligned, if your class relies on a particular alignment; in this case you may want to use a vector of the datatype itself (like
float
). - No, reserve is not necessary here; resize will automatically grow the capacity as necessary, in exactly the same way.
- Before C++03, technically not (but in practice yes). Since C++03, yes.
Incidentally, though, memcpy_s
isn't the idiomatic approach here. Use std::copy
instead. Keep in mind that a pointer is an iterator.
Starting in C++17, std::byte
is the idiomatic unit of opaquely typed storage such as you are using here. char
will still work, of course, but allows unsafe usages (as char
!) which byte
does not.
Besides what other answers mention, I would recommend you to use std::vector::assign
rather than std::vector::resize
and memcpy
:
void MyClass::OnImageReceived(unsigned char *pPixels, unsigned int uPixelCount)
{
m_pImageBuffer.assign(pPixels, pPixels + uPixelCount);
}
That will resize if necessary, and you would be avoiding the unnecessary 0
initialization of the buffer caused by std::vector::resize
.
Using a vector
in this case is fine. In C++ the storage is guaranteed to be contigious.
I would not both resize
and reserve
, nor would I memcpy
to copy the data in. Instead, all you need to do is reserve
to make sure you don't have to reallocate many times, then clear out the vector
using clear
. If you resize
, it will go through and set the values of every element to their defaults -- this is unnecesarry here because you're just going to overwrite it anyway.
When you're ready to copy the data in, don't use memcpy
. Use copy
in conjunction with back_inserter
into an empty vector
:
std::copy (pPixels, pPixels + uPixelCount, std::back_inserter(m_pImageBuffer));
I would consider this idiom to be much closer to canonical than the memcpy
method you are employing. There might be faster or more efficient methods, but unless you can prove that this is a bottleneck in your code (which it likely won't be; you'll have much bigger fish to fry elsewhere) I would stick with idiomatic methods and leave the premature micro-optimizations to someone else.