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...
}
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" .
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With