views:

85

answers:

4

I have a class with a vector of pointers to objects. I've introduced some elements on this vector, and on my main file I've managed to print them and add others with no problems. Now I'm trying to remove an element from that vector and check to see if it's not NULL but it is not working.

I'm filling it with on class Test:

Other *a = new Other(1,1);
Other *b = new Other(2,2);
Other *c = new Other(3,3);

v->push_back(a);
v->push_back(b);
v->push_back(c);

And on my main file I have:

Test t;
(...)

Other *pointer = t.vect->at(0);

delete t.vect->at(0);
t.vect->erase(t.vect->begin());

if (pointer == NULL) { cout << "Nothing here.."; } // Never enters here..
+2  A: 

The deletion of memory pointed by a pointer, doesn't set the pointer to NULL.

AraK
+4  A: 

Deleting a pointer doesn't have to zero it, it just frees the memory assigned there. Using pointer is undefined after the delete though, as the memory is free to be used for other things. Technically the C++ spec intentionally leaves it up to implementations whether they want to zero a deleted pointer or not, but practically none that I know of do so

Michael Mrozek
Right. In that case is there any way so I can do what I pretend?
dmessf
I'm not sure what you're trying to do, what's the point of that check?
Michael Mrozek
Anyway note that the pointer in the vector is deleted, but it's a completely different copy of the same address which is checked. No way is the C++ runtime going to search your entire program for every copy of the address, and set them all to null.
Steve Jessop
+1  A: 

You set pointer equal to the address of something, and never touched it again, so of course it won't be null. The fact that you then did something to the object is irrelevant.

Using simple pointers, there is no safe way for pointer to determine whether the object it once pointed to has been deleted. The simplest way to do what you seem to want to do is by leaving it to the containers: if you're interested in that object, search for pointer in the vector to see whether it's still there (and don't delete the object without erasing the corresponding element from the vector, or you'll have the same problem all over again).

Beta
A: 

To overcome the checking a deleted ptr problem you could use boost::shared_ptr.

Instead of delete use .reset() and to check if the ptr is still valid use .get()
(Actually you can just use if(p) where p is the shared_ptr because it has a conversion to bool)

hamishmcn