According to the following test, it seems that a std::vector<int> increases its capacity in this way:
- it happens when we push_back() and the capacity is already full (i.e. v.size() == v.capacity()), it has to be noted that it doesn't happen a little bit before
- the capacity increases to 1.5 times the previous capacity
Question: why this 1.5 factor? Is it implementation-dependent? Is it optimal?
Also, is there a way to analyze, in this code, when exactly a reallocation happens? (sometimes maybe the capacity can be increased without moving the first part of the array)
Note: I'm using VC++ 2013
I think an important aspect to the answer of why the factor is 1.5 is preferred over 2.0, is that the standard c++ allocator model does not support a realloc function:
Realloc- in Standard allocator
If it would exist, and it would be used in std::vector, the mentioned memory fragmentation problem would be minimized in all cases where the factor 1.5 is better compared to e.g. factor 2.0 capacity increase.
The factor of 1.5 (or more precisely the golden ratio) is just optimum when the buffer is always relocated on every buffer size increase (as the other answers explain).
With realloc and if there is space after the current memory block, it would just be enlarged without copying. If there is no space, realloc call would of course move the datablock. However then the free'd blocks (if this happens multiple times) would not be contiguous anyway. Then it doesnt matter whether 1.5 or 2 is the factor for buffer enlargement... Memory is fragmented anyways.
So a realloc approach in std::vector would help wherever the factor 1.5 has the advantage over 2.0 and would save the data copy.
'프로그래밍(Programming) > c++, 11, 14 , 17, 20' 카테고리의 다른 글
[C++20] 모듈(module) (0) | 2023.03.18 |
---|---|
Type Conversion - compile time (Dynamic Cast 과 유사) (0) | 2022.10.17 |
using shared_ptr with pure virtual base class (0) | 2022.08.24 |
C++ 락(std::lock, std::unique_lock, std::lock_guard, condition_variable...) (0) | 2022.08.11 |
C++ "Virtual functions but no virtual destructors" (0) | 2022.04.27 |