Custom string literals: two EasyHacks
In the previous part of the series on C/C++ strings, I described the string literal, plus how and why to use them. Then I introduced the new custom string literals and their benefits:
Using the New Custom O[U]String Literals
In this post, I am going to discuss two EasyHacks dedicated to the use of the new O[U]String literals in the code.
- 158067 – Replace O(U)StringLiterals with custom O(U)String literals in code
- 158068 – Replace string literals with custom O(U)String literals in code
For tdf#158067, the idea is to use _oustr
and _ostr
suffixes instead of defining O[U]StringLiteral
variables, and using them later.
For example,
OUString foo = "abc";
Becomes:
static constexpr OUStringLiteral FOO_STR = "abc"; ... OUString foo(FOO_STR);
The first line is using a compile time constant, but it is not clean, easy and not always desirable. After the introduction of the new shortcuts _ustr
and _ostr
, there is a new way to to create string literals in shorter form, available with C++20 standard. As C++20 is now the baseline for LibreOffice code, the new way is usable in the LibreOffice code.
For tdf#158068, the goal is to avoid C string literals, and replace those literals with the new O(U)String
literals with appropriate prefixes. The benefit of doing that is to avoid run-time initialization of O[U]Strings
, and do it in the compile time.
OUString foo("abc");
should become:
OUString foo(u"abc"_ustr);
Don’t Change Every O[U]String literal!
There are tests for O[U]StringLiterals that should not be touched at the moment. Eventually, developers will change them alongside the O[U]StringLiteral data types themselves.