static_assert(sizeof(std::array<int,5>)==5*sizeof(int));
the above mitigates against having any padding on the end of a std::array
. No major compiler will cause the above to fail to this date, and I'd bet won't in the future.
If and only if the above fails, then std::vector<std::array<int,5>> v(2)
will have a "gap" between the std::array
s.
This doesn't help as much as you'd like; a pointer generated as follows:
int* ptr = &v[0][0];
only has a domain of validity up to ptr+5
, and dereferencing ptr+5
is undefined behavior.
This is due to aliasing rules; you aren't allowed to "walk" past the end of one object into another, even if you know it is there, unless you first round-trip to certain types (like char*
) where less restricted pointer arithmetic is permitted.
That rule, in turn, exists to allow compilers to reason about what data is being accessed through which pointer, without having to prove that arbitrary pointer arithmetic will let you reach outside objects.
So:
struct bob {
int x,y,z;
};
bob b {1,2,3};
int* py = &b.y;
no matter what you do with py
as an int*
, you cannot legally modify x
or z
with it.
*py = 77;
py[-1]=3;
std::cout << b.x;
the complier can optimize the std::cout
line to simply print 1
, because the py[-1]=3
may attempt to modify b.x
, but doing so through that means is undefined behavior.
The same kind of restrictions prevent you from going from the first array in your std::vector
to the second (ie, beyond ptr+4
).
Creating ptr+5
is legal, but only as a one-past-the-end pointer. Comparing ptr+5 == &v[1][0]
is also not specified in result, even though their binary values are absolutely going to be identical in every compiler on every major hardware system.
If you want to go futher down the rabbit hole, it isn't even possible to implement std::vector<int>
within C++ itself due to these restrictions on pointer aliasing. Last I checked (which was before c++17, but I didn't see a resolution in C++17) the standard committee was working on solving this, but I don't know the state of any such effort. (This is less of a problem than you might think, because nothing requires that std::vector<int>
be implemented in standard-compliant C++; it must simply have standard-defined behavior. It can use compiler-specific extensions internally.)