3 ms·
"pointer is not giving you much information about the availability of the data behind it" "elaborate on this with an actual concrete example" The pointer may
by xaedes 6y ago
"pointer is not giving you much information about the availability of the data behind it"
"elaborate on this with an actual concrete example"
The pointer may get invalidated, for example by reallocation of the underlying data structure:
#include <iostream>
#include <vector>
struct ItemPrinter
{
int* ptr;
void print()
{
std::cout << (*ptr) << std::endl;
};
};
int main()
{
std::vector<int> items{1};
ItemPrinter foo{&(items[0])};
while(items.size()<1000)
{
foo.print();
items.push_back(2);
}
}
When push_back exceeds the vector capacity, it needs to reallocate and `foo.ptr` gets invalidated.
Output when executed via http://cpp.sh/ http://cpp.sh/
1
0
1
1
35557904
35557904