Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to initialize QString

I have a QString variable as struct member.

What is the best way to initialize it with default value:

struct Foo
{
   QString name = "name";
   // or
   // QString name = QStringLiteral("name");
   // or
   // QString name = QLatin1String("name");
   // or something else...
}
like image 837
Vadym Senkiv Avatar asked Nov 13 '18 11:11

Vadym Senkiv


People also ask

How do I set QString to null?

To create a null QString just default initialize it: QString phoneNumber; // or if you already have a QString variable and want to 'clear' it: phoneNumber = QString(); Note that QString::number(0) is decidedly not null - it creates a QString with the value "0" .

How do I check if QString is empty?

QString() creates a string for which both isEmpty() and isNull() return true . A QString created using the literal "" is empty ( isEmpty() returns true ) but not null ( isNull() returns false ). Both have a size() / length() of 0.

How do you split a QString?

To break up a string into a string list, we used the QString::split() function. The argument to split can be a single character, a string, or a QRegExp. To concatenate all the strings in a string list into a single string (with an optional separator), we used the join() function.

What is QString C++?

The QString class provides an abstraction of Unicode text and the classic C '\0'-terminated char array. More... All the functions in this class are reentrant when Qt is built with thread support.


1 Answers

QStringLiteral will have the lowest runtime overhead. It is one of the few literal QString initializations with O(1) cost. QLatin1String will be pretty fast, but have O(N) cost in length of the string. The intiialization with C string literal will have the highest O(N) cost and is equivalent to IIRC QString::fromUtf8("…"). The 2nd and 3rd initialization also adds an O(N) memory cost, since a copy of the string is made (!). Whatever “savings” you made in executable size thus promptly vanish as the program starts up :(

Initialization via QStringLiteral wins, although you may want to leverage modern C++11 custom literals to make it shorter. Resist the urge to use a macro for it: it’d be an extremely misguided approach as you pollute the global namespace with a short symbol.

like image 86
Kuba hasn't forgotten Monica Avatar answered Sep 27 '22 19:09

Kuba hasn't forgotten Monica