I want to know the precise meaning that
std::vector<T>::shrink_to_fit(new_capacity)
would invalidate reference.
"If a reallocation happens, all iterators, pointers and references related to the container are invalidated. Otherwise, no changes." --
http://www.cplusplus.com/reference/vector/vector/shrink_to_fit/
Test code:
#include <vector>
#include <iostream>
class Test {
public:
Test(const std::vector<int>& a) : _a(a) {}
void print() const {
std::cout << "[";
for (auto x:_a) std::cout << " " << x;
std::cout << " ]\n";
}
const std::vector<int>& _a;
};
int main() {
std::vector<int> a;
a.reserve(100);
for (int i = 0; i < 10; ++i) a.push_back(i);
Test t(a);
t.print();
a.shrink_to_fit();
t.print(); // will this always work as expected?
}
If new_capacity
is less than old_capacity
(so the capacity of the vector
shrinks), can the reference (the _a
attribute of the test class) be invalidated?