Note that there are some explanatory texts on larger screens.

plurals
  1. POIs it good practice to use std::vector as a simple buffer?
    primarykey
    data
    text
    <p>I have an application that is performing some processing on some images.</p> <p>Given that I know the width/height/format etc. (I do), and thinking just about defining a buffer to store the pixel data:</p> <p>Then, rather than using <code>new</code> and <code>delete []</code> on an <code>unsigned char*</code> and keeping a separate note of the buffer size, I'm thinking of simplifying things by using a <code>std::vector</code>.</p> <p>So I would declare my class something like this:</p> <pre><code>#include &lt;vector&gt; class MyClass { // ... etc. ... public: virtual void OnImageReceived(unsigned char *pPixels, unsigned int uPixelCount); private: std::vector&lt;unsigned char&gt; m_pImageBuffer; // buffer for 8-bit pixels // ... etc. ... }; </code></pre> <p>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:</p> <pre><code>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(&amp;m_pImageBuffer[0], m_pImageBuffer.size(), pPixels, uPixelCount); // ... process image etc. ... } </code></pre> <p>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:</p> <ol> <li>Is this a valid application of <code>std::vector</code> or is there a more suitable container?</li> <li>Am I doing the right thing performance-wise by calling <code>reserve</code> <em>and</em> <code>resize</code>?</li> <li>Will it <em>always</em> be the case that the underlying memory is consecutive so I can use <code>memcpy_s</code> as shown?</li> </ol> <p>Any additional comment, criticism or advice would be very welcome.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload