M
M
maaGames2021-10-04 13:31:18
C++ / C#
maaGames, 2021-10-04 13:31:18

How to calculate required buffer size for monotonic_buffer_resource?

After all, not only data is written to this buffer, but also pointers to the next / previous nodes and something else, if the container needs it. Is it possible to somehow get the size of the "node" from the container in runtime/compiletime in order to multiply it by the expected number of elements and make a buffer of the required size? A node is not an object with stored data, but user data + service data necessary to implement the container.

constexpr int total_nodes = 10;

    // Нужно создать буфер достаточного размера, при этом это не sizeof(int)*total_nodes

    constexpr int enoughSize = total_nodes * ???;// enough to fit in all nodes

    std::array<std::byte, enoughSize> buffer;
    buffer.fill( std::byte{0} );
    std::pmr::monotonic_buffer_resource mbr{buffer.data(), buffer.size()};
    std::pmr::polymorphic_allocator<int> pa{&mbr};
    std::pmr::list<int> list{pa};

    for( int i=0; i < total_nodes; ++i )
    {
        list.push_back( i );
    }


There you need to take into account the size and number of pointers in each node, if any. Those. bit depth, alignment, and so on. For example, here is the code
std::array<std::byte, enoughSize> buffer;
  std::pmr::monotonic_buffer_resource mbr{buffer.data(), buffer.size()};
  std::pmr::polymorphic_allocator<int> pa{&mbr};
  std::pmr::map<int,int> map{pa};
        map[1]=1;
        map[2]=2;

Requires a buffer of (minimum) 80 bytes on x86 and 132 bytes on x64. I checked this in fact, how much was used in the buffer.

I know the number of elements and the data is not removed from the container, so I can allocate the buffer right away... but I can't figure out the required size.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
res2001, 2021-10-04
@res2001

For example, std::vector defines the type value_type - this is just the type of the element of the vector.
You can use constructs like:

sizeof(decltype(vector_val)::value_type)
или
sizeof(decltype(vector_val.back()))

to calculate the element size of a vector, where vector_val is an existing vector instance

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question