Is there an STL container that stores an array of elements in contiguous memory where the element size is specified at runtime?

后端 未结 3 459
青春惊慌失措
青春惊慌失措 2021-01-22 20:49

I\'m trying to create container that looks close to how my file spec works. It\'s like a vector but the type of the elements is defined by a hashtable.

If I knew the typ

3条回答
  •  南方客
    南方客 (楼主)
    2021-01-22 21:31

    Is there an STL container that stores an array of elements in contiguous memory where the element size is specified at runtime?

    No.

    What you're asking for looks like a specific implementation of a memory pool. Maybe the Boost.Pool library or other implementations would be of use to you? Writing your own one shouldn't be hard if you're used to work with raw memory and C++-specific creation/destruction of objects.

    To answer your questions:

    Does anything do this already?

    To me the idea looks like a memory pool. There are tons of kind of memory pools so the implementation you'll want totally depends on your specific needs.

    Is this a bad idea? Should I just create a vector and new up each element? I expect to have millions of elements. The range of sizes of foo will be 20 to 200 bytes.

    It's not a bad idea if you're wanting to limit memory fragmentation. Pools are often used to fix this and other memory-organisation related prolems.

    For example, it's very frequent in video games to do this, mostly on console but also on PC if you need high performance or a lot of memory.

    I just wouldn't recommand bothering if you're making a prototype or if you don't have tons of data to allocate. If you do, then maybe first implementing the simplest allocation (with vectors and new) hidden behind a factory would be nice and would allow you to replace the factory implementation by using a pool. That way you first check that everything work, then optimize.

提交回复
热议问题