简体   繁体   中英

Should i use std::vector of std::unique_ptr<T[]> if memory is sparse and i'm not going to resize

Suppose i have physics engine which need to solve systems of linear equation size of which is unknown in forward, but after i know it, i will not change it. One such matrix may easily take hundreds of kilobytes. The problem with vector is that i never really know how much space it has allocated and i don't want to allocate more than needed.

Most discussion tell us to use std::vector , but should i use std::unique_ptr<T[]> instead? Hm... maybe i need to use std allocator as this answer suggests?


From the standard:

After reserve(), capacity() is greater or equal to the argument of reserve if reallocation happens; and equal to the previous value of capacity() otherwise.

So it is not the option for me to use reserve.

I also found that there was proposition for dynarray which should have handled my case, and for now that is the way i'm going to take, if no other propositions will come.

From what you have said in your question, I would say that usage of std::vector should be fine: as soon as you know the size, you can reserve it in your vector(s) and there will ne no additional overhead because no allocation will never happen again in that part.

Of course, as a vector does allocate a raw array under the hood, you can also allocate it as soon as the size if known and deallocate it when done, but the memory gain should be limited to size of the vector struct itself, at least for 1-D arrays.

If you have huge multi-dimensional arrays, the gain will be higher because you will have on vector struct per row (and per plane in 3-D array), so using raw arrays instead of vector of size n n will be n sizeof(vector)

But it is a low level optimization, so you should only worry for that after all higher level optimizations have been exhausted (storing only one half for symetric matrixes for example).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM