Lifetime of std::span
A std::span
is just a view onto an array, right?
It’s new in C++20, so at work-work where we try
to be modern where possible, I wrote an access
function for a static array, and had it return a
std::span
object.
Ha ha, welcome to UB.
#include <span>
static int my_integers[] = { 1, 2, 332 };
std::span<int> get_integers() { return my_integers; }
int main()
{
auto oneIt = get_integers().begin();
auto twoIt = ++(get_integers().begin());
return *oneIt + *twoIt;
}
The iterator oneIt
is obtained from a std::span
object
whose lifetime ends at the end of the full expression.
There does not seem to be any language tying the
iterator to the lifetime of the underlying contiguous objects,
so the iterator is invalid later.
Everything I’ve tried seems to work, but that’s the whole problem with UB.