I have a function which returns a pointer and a length, and I want to call std::string::assign(pointer, length)
. Do I have to make a special case (calling clear
) when length is zero and the pointer may be nullptr?
The C++ standard says:
21.4.6.3 basic_string::assign
basic_string& assign(const charT* s, size_type n);
Requires: s points to an array of at least n elements of charT.
So what if n
is zero? What is an array of zero characters and how does one point to it?
Is it valid to call
s.assign(nullptr, 0);
or is it undefined behavior?
The implementation of libstdc++ appears not to dereference the pointer s
when the size n
is zero, but that's hardly a guarantee.