According to https://en.cppreference.com/w/cpp/container/vector/data, the underlying pointer is not guaranteed to be nullptr if the size is 0
If size() is 0, data() may or may not return a null pointer.
but does that apply to the default initialized std::vector with no elements? or does that simply state that if all elements of the vector are erased, the underlying pointer may not become nullptr?
Consider the following line:
std::vector<int> fooArr;
int* fooArrPtr = fooArr.data();
is it guaranteed that fooArrPtr
is equal to nullptr?
No.
The standard guarantees that a default-initialised std::vector
has size()
equal to zero, but that doesn't require that data()
will return nullptr
.
There is nothing in the standard that prevents (and "not preventing" is not equivalent to "requiring") a default-constructed vector having zero .size()
and non-zero capacity()
. In such a case, it would be feasible for .data()
to return a pointer to the allocated memory (which will be non-null, but dereferencing it will still have undefined behaviour since .size()
is zero [and allocated capacity is not required to be initialised]).
If you want to test if a vector has zero size, use .size()
or .empty()
. Don't call .data()
and compare the result with nullptr
.