How is dynamic memory managed in std::vector?

后端 未结 4 1534
南笙
南笙 2021-01-03 08:52

How does std::vector implement the management of the changing number of elements: Does it use realloc() function, or does it use a linked list?

Thanks.

4条回答
  •  半阙折子戏
    2021-01-03 09:23

    One of the hard-and-fast rules of vectors is that the data will be stored in one contiguous block of memory.

    That way you know you can theoretically do this:

    const Widget* pWidgetArrayBegin = &(vecWidget[0]);
    

    You can then pass pWidgetArrayBegin into functions that want an array as a parameter.

    The only exception to this is the std::vector specialisation. It actually isn't bools at all, but that's another story.

    So the std::vector will reallocate the memory, and will not use a linked list.

    This means you can shoot yourself in the foot by doing this:

    Widget* pInteresting = &(vecWidget.back());
    vecWidget.push_back(anotherWidget);
    

    For all you know, the push_back call could have caused the vector to shift its contents to an entirely new block of memory, invalidating pInteresting.

提交回复
热议问题