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

后端 未结 8 597
慢半拍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:45

    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.

提交回复
热议问题