c++stringview

Can i construct a string_view from a nullptr?


I just found that xcode/clang does not allow to construct a std::string_view from a char* nullptr. I would expect that this sets size() to 0 and returns a null for data(), and this is how also how gcc 7.2 on my Ubuntu Linux box implemented it.

I checked http://en.cppreference.com/ but couldn't find any comment about this, so what is the standard saying?


Solution

  • Well, yes and no. You cannot pass a null pointer to std::string_view's constructors, because that will violate their preconditions; see constructor 2 and 3 in [string.view.cons].

    But std::string_view's default constructor sets size to zero and null for its data, so you will have to use that constructor instead, or use this workaround/trick:

    std::string_view().swap(your_string);