string_view cheat sheet

Stephan Bergmann sbergman at redhat.com
Wed Dec 30 10:48:11 UTC 2020


With the recent increase in using std::string_view and 
std::u16string_view (instead of OString and OUString) as function 
parameter types, there are some patterns how to address build failures 
caused by such changes:

* Passing char arrays to std::u16string_view:

** For a string literal, replace

   f("...")

with

   f(u"...")

** If the string literal is defined as a macro

   #define M "..."

either change the macro definition to

   #define M u"..."

or, if the macro is also used in other places that keep needing a narrow 
string literal, change the use to

   f(u"" M)

** For any other array like

   static constexpr char a[] = "..."

either change it to

   static constexpr char16_t a[] = u"..."

or, if the array is also used in other places that keep needing a narrow 
string literal, massage the overall code until you end up with 
consistent requirements for the type of a :)

* Concatenation:  If neither of the two arguments to operator + is one 
of our rtl types related to string concatenation, as in

   void f(std::u16string_view s) { ...
     "..." + s + ...

then wrap the leftmost argument in a O[U]String::Concat marker:

     OUString::Concat("...") + s + ...

* From concatenation to string_view:  If the result of a concatenation 
shall be used as a string_view, as in

   void f(std::u16string_view s);
   ...
   f(a + b)

we need a temporary that holds the concatenated characters in a 
consecutive range of memory:

   f(OUString(a + b))

And all of that similarly for std::string_view.

(And, by the way, std::string_view and std::u16string_view are meant to 
be cheap to copy and to be passed by value.)



More information about the LibreOffice mailing list