Home > OS >  Does C standard guarantee that std::vector's underlying pointer initialized as nullptr
Does C standard guarantee that std::vector's underlying pointer initialized as nullptr

Time:01-23

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?

CodePudding user response:

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(). (or, if the vector is empty, produce a null pointer, otherwise call .data()).

CodePudding user response:

When an empty vector is instantiated, no memory is allocated. Then clearing all the elements doesn't mean that the vector release its internal memory (this remains available when new elements will be inserted). The memory will be released only when the destructor is called.

To make a long story short, you cannot use data() to check if a vector is empty.

Furthermore, it is not even advisable to check if a vector has had some members in its existance depending if data() returns you a nullptr or less. You cannot be sure that the internal template implementation always grants you this property.

  •  Tags:  
  • Related