Reputation: 1065
I'm new to c++ and find it confusing handling pointers on stl containers. How does stl containers handle pointers?
Point *p1 = new Point(10, 10);
std::vector<Point*> points;
points.push_back(p1);
delete p1; // or delete points[0]
std::cout << points[0]->getID() << "\n"; //why does this still display 10, 10 after deleting above?
std::cout << p1->getID(); //ofcourse, this one will output garbage
//getID method displays xy coordinates given as parameters when object is created
//The result displayed
10, 10
-1, 12337
Upvotes: 0
Views: 1223
Reputation: 67211
After the delete statement, Its upto the compiler to when to reuse that freed memory. so it is undefined behaviour.
Upvotes: 1
Reputation: 227370
Standard library containers do nothing special about pointers. If the pointers point to dynamically allocated objects, these have to be deleted by someone at some point. Who, when and how really depends on the details of the application, but it is usual to automate this process by use of smart pointers.
std::cout << points[0]->getID() << "\n"; //why does this still display 10, 10 after deleting above?
points[0]
has been deleted, and dereferencing a deleted pointer is undefined behaviour. That means anything could happen. What has probably happened is that the memory you have released by calling delete
has not been reclaimed for anything, so the data are still there. You cannot rely on that behaviour.
Upvotes: 0
Reputation: 104698
the container, if declared as std::vector<Point*> points;
will treat it like declaring Point* point(new Point(blah));
, meaning you will need some matching delete
in this context. of course, you should be using either a) values in that vector std::vector<Point> points;
, or b) smart pointers. in most cases, the former (a).
in this case, you would write delete p1;
, and the access of the deleted object is undefined behavior -- any access/use of that object after the delete is useless. you're lucky if the program crashes and points out the error to you.
Upvotes: 1