I have an application that is performing some processing on some images.
Given that I know the width/height/format etc. (I do), and thinking just about defining a buffer to store the pixel data:
Then, rather than using new
and delete []
on an unsigned char*
and keeping a separate note of the buffer size, I'm thinking of simplifying things by using a std::vector
.
So I would declare my class something like this:
#include <vector>
class MyClass
{
// ... etc. ...
public:
virtual void OnImageReceived(unsigned char *pPixels,
unsigned int uPixelCount);
private:
std::vector<unsigned char> m_pImageBuffer; // buffer for 8-bit pixels
// ... etc. ...
};
Then, when I received a new image (of some variable size - but don't worry about those details here), I can just resize the vector (if necessary) and copy the pixels:
void MyClass::OnImageReceived(unsigned char *pPixels, unsigned int uPixelCount)
{
// called when a new image is available
if (m_pImageBuffer.size() != uPixelCount)
{
// resize image buffer
m_pImageBuffer.reserve(uPixelCount);
m_pImageBuffer.resize(uPixelCount, 0);
}
// copy frame to local buffer
memcpy_s(&m_pImageBuffer[0], m_pImageBuffer.size(), pPixels, uPixelCount);
// ... process image etc. ...
}
This seems fine to me, and I like that fact that I don't have to worry about the memory management, but it raises some questions:
- Is this a valid application of
std::vector
or is there a more suitable container? - Am I doing the right thing performance-wise by calling
reserve
andresize
? - Will it always be the case that the underlying memory is consecutive so I can use
memcpy_s
as shown?
Any additional comment, criticism or advice would be very welcome.
std::vector::assign
instead ofmemcpy
and (sometimes) resize? That will resize if necessary, and avoid the unnecessary initialization of the buffer.assign
a block of memory to thevector
? Can you show me the syntax?memcpy_s
will ensure that you don't change things around and introduce a buffer overrun later on, long after you've forgotten what was going through your head when you originally wrote it.memcpy_s
does not check the return value; if you forget why you resized the buffer and end up trying to write more data than the buffer will hold this call won't overwrite the buffer; all it will do is quietly produce corrupt data. There's no magic formula for writing robust code. You have to think.