About this blog

Save duplicate questions from disappearing from Google

Is null pointer a valid iterator?

Question

I'm implementing std::vector-like class. Its iterators are just plain pointers. The problem is that if the vector is empty (there is no allocated buffer for elements) it returns nullptr as begin and end iterators. Are null pointers valid iterators?

I tried to learn std::vector source code in GNU C++ standard library. It looks like they use the same approach with null pointers.

But what about using std::distance with null pointers? It is defined as last - first for random access iterators. But it is not valid to subtract null pointers (at least in pure C). Ok, they can compare iterators before subtracting (comparing null pointers is valid), and if they are the same, return 0 without subtracting.

But anyway, last - first is assumed to be valid expression for random access iterators, but it is not because subtracting null pointers is undefined behavior.

If null pointers can't be used as iterators, what can I use instead?

Answer

It's valid to subtract null pointers in C++. It's still unclear if there are other reasons why null pointer can't be a valid iterator. There are probably no. If you are still interested, vote to reopen the question or write your opinion at meta.stackoverflow.com.