How to manage a large buffer in C ++?

If I need a large buffer in my C ++ program, which one is better?

  • Allocate the buffer on the heap and save the link to this buffer in the class that uses it.

  • Highlight a static buffer and make it global.

+4
source share
5 answers

How about: 3. Use a vector.

[Addition edited: or boost :: array is a good option if you are satisfied with the dependency]

+14
source

The disadvantage of a static buffer is that you never know exactly when it will be deleted, if you want to use this buffer while destroying an object, it may already disappear. Therefore, for more control, I would choose option 1.

+2
source

I prefer heap allocation for many reasons -

The main reason I prefer this is because at runtime it gives you the opportunity to make sure that the distribution was successful. When you try to allocate memory, it will be obvious if for some reason it does not work, and you can process it much more elegantly than if you were making a static buffer.

It also allows you to distribute buffers of various sizes and reallocate / free, if possible, at a later time.

+2
source

What does your program do? If the buffer lasts as long as the application and you know its size at compile time, feel free to use a static buffer.

Also, as already mentioned, consider using a vector (unless you have benchmarks showing that performance is too low) to prevent buffer overflows.

+1
source

When working with large amounts of memory, you should look at two things: the life cycle, how often you create and recreate this buffer. As memory becomes fragmented, a time may come when you try to allocate a buffer of, say, 512 MB, but you cannot, because your allocator cannot find 512 MB of adjacent address space. That's why @onebyone the idea of ​​using vectors is sometimes better. If you can reduce the size of your space to sizes (not literally) bytes, you will get the flexibility to manage your memory.

However, I would almost never recommend maintaining a large static buffer. He asks for trouble.

+1
source

All Articles