I experimented with pointer vectors and came across the following behavior, which I don't quite understand:
#include <iostream> #include <vector> int main() { std::vector<int*> vec; int* p1 = new int; *p1 = 100; vec.push_back(p1); std::cout << *vec[0] << std::endl; delete p1; std::cout << *vec[0] << std::endl; int* p2 = new int; *p2 = 200; std::cout << *vec[0] << std::endl; return 0; }
Using the MinGW C ++ compiler (g ++), this gave me the following result:
100 5640648 200
Now, of course, the actual element vec[0] not deleted when the pointer was deleted, but note that p2 is not inserted into the vector at all. However, printing the value of the first element returns the value of this seemingly unbound pointer! Also, restructuring the code a bit to declare p2 before removing p1 does not give this behavior.
Just to make sure, I also compiled this with MSVC ++, which gave me the following (expected) output:
100 5484120 5484120
Does anyone have an explanation for the first exit?
source share