Is it good practice to use std::vector as a simple buffer?

后端 未结 8 595
慢半拍i
慢半拍i 2021-01-31 07:41

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

相关标签:
8条回答
  • 2021-01-31 07:55

    Please, consider this:

    void MyClass::OnImageReceived(unsigned char *pPixels, unsigned int uPixelCount)
    {
        // called when a new image is available
        if (m_pImageBuffer.size() != uPixelCount) // maybe just <  ??
        {
            std::vector<unsigned char> temp;
            temp.reserve(uPixelCount);        // no initialize
            m_pImageBuffer.swap(temp) ;       // no copy old data
        }
    
        m_pImageBuffer.assign(pPixels, pPixels + uPixelCount);  // no reallocate
    
        // ... process image etc. ...
    }
    

    My point is that if you have a big picture and need a litter bigger pic, your old pic will get copy during the reserve and/or resize into the new allocated memmory, the excess of memmory initialized, and then rewrited with the new pic. You colud directly assing, but then you will no be able to use the info you have about the new size to avoid posible reallocations (maybe the implementation of assign is allready optimize for this simple case ????).

    0 讨论(0)
  • 2021-01-31 08:07

    std::vector was MADE to be used in such cases. So, yes.

    1. Yes, it is.

    2. reserve is unnecessary in your case.

    3. Yes, it will.

    0 讨论(0)
提交回复
热议问题