Choice between vector::resize() and vector::reserve()

后端 未结 4 1455
遥遥无期
遥遥无期 2020-11-22 05:01

I am pre-allocating some memory to my a vector member variable. Below code is minimal part

class A {
  vector t_Names;
public:
           


        
4条回答
  •  自闭症患者
    2020-11-22 05:45

    reserve when you do not want the objects to be initialized when reserved. also, you may prefer to logically differentiate and track its count versus its use count when you resize. so there is a behavioral difference in the interface - the vector will represent the same number of elements when reserved, and will be 100 elements larger when resized in your scenario.

    Is there any better choice in this kind of scenario?

    it depends entirely on your aims when fighting the default behavior. some people will favor customized allocators -- but we really need a better idea of what it is you are attempting to solve in your program to advise you well.

    fwiw, many vector implementations will simply double the allocated element count when they must grow - are you trying to minimize peak allocation sizes or are you trying to reserve enough space for some lock free program or something else?

提交回复
热议问题