Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can i construct a string_view from a nullptr?

Tags:

c++

string

view

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?

like image 353
Lothar Avatar asked Nov 11 '17 17:11

Lothar


1 Answers

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);
like image 82
Rakete1111 Avatar answered Oct 17 '22 02:10

Rakete1111