Issue 183256
Summary clang-22 regression: std::vector<T>::append_range reallocates too eagerly
Labels new issue
Assignees
Reporter haubenmi
    In b6bfb199ccc888021690dbc5428db4f300c7f8f2, the implementation of `append_range` was changed to no longer use `insert_range` internally.
However, I believe the new condition `if (__len < __cap_ - __end_)` is slightly wrong, and should read `<=` instead.

In our code base, we are reserving exactly as many elements in a vector as we will later insert via multiple `append_range` calls.
However, since the above mentioned commit, the vector will internally grow and use twice the memory we anticipated (and need).
This is a problem for us, as we want to bound the memory that this specific code path uses.

I believe that according to https://en.cppreference.com/w/cpp/container/vector/reserve.html
> After a call to reserve(), insertions will not trigger reallocation unless the insertion would make the size of the vector greater than the value of [capacity()](https://en.cppreference.com/w/cpp/container/vector/capacity.html).
this behavior even violates the standard (if cppref == standard).

Example C++ program that highlights the issue:
```
#include <iostream>
#include <vector>
using namespace std;

int main() {
  {
    cout << "scenario: push_back\n";
    vector<int> v;
    v.reserve(10);
    for (int i = 0; i < 10; ++i) {
        v.push_back(i);
        cout << "Size: " << v.size() << " Capacity: " << v.capacity() << "\n";
    }
  }
  {
 cout << "scenario: append_range\n";
    array<int, 10> arr;
 vector<int> v;
    v.reserve(10);
    v.append_range(arr);
    cout << "Size: " << v.size() << " Capacity: " << v.capacity() << "\n";
 }
}
```
Output of this program after compiling with `clang++ -std=c++23`:
```
scenario: push_back
Size: 1 Capacity: 10
Size: 2 Capacity: 10
Size: 3 Capacity: 10
Size: 4 Capacity: 10
Size: 5 Capacity: 10
Size: 6 Capacity: 10
Size: 7 Capacity: 10
Size: 8 Capacity: 10
Size: 9 Capacity: 10
Size: 10 Capacity: 10
scenario: append_range
Size: 10 Capacity: 20
```
_______________________________________________
llvm-bugs mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs

Reply via email to