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.
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?