Why is my pointer 0, not nullptr?

I have a vector of pointers to some objects. Since some of the entries in the vector are sometimes unused, i initially fill the vector with nullptr's using std::fill. I'm not sure whether that is actually needed, but i did it anyway just to be sure.

However, sometimes i need to do a check looking like this.

1
2
  if (my_vector.at(x) == nullptr) //some abortion code
  else //do some stuff with my_vector.at(x) 

However for some reason the check evaluates to false, even if my_vector.at(x) has been initialized to a nullptr. If i change the check to my_vector.at(x) == 0, then my code suddenly behaves as expected? Why is that?
Have you verified that the pointer in question still contains its original nullptr value when it is being checked? It's possible that your pointers are being initialized/invalidated elsewhere in your code.
However for some reason the check evaluates to false, even if my_vector.at(x) has been initialized to a nullptr. If i change the check to my_vector.at(x) == 0, then my code suddenly behaves as expected? Why is that?


This must not be the whole story. nullptr is 0.. they're the same thing. The only thing that's different is the type. Any comparison to one of them would equal a comparison to the other.

See this example, note how it prints everything you'd expect it to:
http://ideone.com/FY13zH


You must be doing something else wrong that you're not telling us.


EDIT:

ModShop's answer is on the nose. The contents of the pointer must be changing somewhere.
Last edited on
You must be doing something else wrong that you're not telling us.

Yes indeed you were right. I had my logic turned around 180 degress, but don't mind that it was very helpful :) now i also understand nullptr a little better.

-edit
BTW is it neccesary to fill the vector with nullptr or can i expect it to not contain any garbage values initially? For example will this code initialize a vector of 20 nullptr's?
 
  std::vector<some_object*> my_vector {20};
Last edited on
http://www.cplusplus.com/reference/vector/vector/vector/
you would be using (2) with val being a null pointer.

f you have doubts, then you can be specific std::vector<some_object*> my_vector {20, nullptr};
Topic archived. No new replies allowed.