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

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

    1. 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).
    2. No, reserve is not necessary here; resize will automatically grow the capacity as necessary, in exactly the same way.
    3. 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.

提交回复
热议问题