I have seen these questions:
Weirdness of the reserve() of vector
Is accessing the raw pointer after std::vector::reserve safe?
How reserve in std::vector works + Accessing vector with []
And a few others. But all of them deal with accessing the elements outside of the reserved space. I am interested in those strictly inside.
For example:
#include <iostream>
#include <vector>
int main()
{
std::vector<int> a;
a.reserve(3);
a[0] = 4;
std::cout << a[0] << ',' << a[1] << ',' << a[2] << '\n';
std::cout << *(a.data()) << '`' << *(a.data() + 1) << '`' << *(a.data() + 2) << '\n';
a[2] = 7;
for(int &i: a)
std::cout << i << ',';
std::cout << '\n';
std::cout << a[0] << ',' << a[1] << ',' << a[2] << '\n';
std::cout << *(a.data()) << '`' << *(a.data() + 1) << '`' << *(a.data() + 2) << '\n';
return 0;
}
This prints:
4,0,0
4`0`0
4,0,7
4`0`7
The empty line is the output of the for
, and it makes sense: I only reserved memory, the vector considers there is no data.
I've been playing with this for an hour already, always staying within the confined space, and it never once crashed. I added -fsanitize=address -Wall -Wpedantic
, no complaints (also on SO, but I lost the link). Also notice that I am directly dereferencing the data()
, and it seems to be fine with it. So I have to wonder, is this undefined behavior?
I suppose the code above will make some cringe (I can't tell), but prettiness is not my goal with this -- it's just a personal goal.
To be more specific, I was trying to convert a Fortran eigenvalue program, but I know maybe two things in Fortran, rounded up, and while switching back and forth between the browser and the compiler, I stumbled across std::vector reserve() and push_back() is faster than resize() and array index, why? and a few similar others. And, sure enough, it works, but when I tried to use []
instead of push_back()
, or insert()
, it went even faster, a lot faster. I know this is a bit of a premature optimization, but I'd rather put out the fire now, while it's hot, rather than later.
So, here I am.