[Development] Introducing qEnvironmentVariable
Thiago Macieira
thiago.macieira at intel.com
Fri Dec 4 19:38:51 CET 2015
I've just pushed a new function called qEnvironmentVariable. It's basically
the equivalent of qgetenv returning a QString. Here's the rule of when to use
it:
A) qEnvironmentVariable:
1) file paths
Always use this function when dealing with environment variables containing
paths, in any OS.
Exception: when writing Unix-only code and you're going to pass that path to a
non-Qt function taking 8-bit file paths (very rare)
2) Windows code
This function is more efficient than qgetenv on Windows because the environment
on Windows is stored already as UTF-16. However, the gains may be quite small
because the C runtime may be keeping both the UTF-16 and locale environments.
3) when you're about to convert to QString anyway
This function does that for you, so you save some keystrokes and parentheses
in your code.
B) qgetenv:
1) when you're going to use as a QByteArray or it doesn't matter
It's ok to continue using qgetenv if you need a QByteArray anyway. Please note
file paths should never be stored in QByteArrays on Windows.
2) Unix code
This function is more efficient than qEnvironmentVariable on Unix because the
environment is stored in 8-bit. Note again the rules above for file paths.
3) converting from 8-bit *without* NFD/NFC conversion
On the extremely rare case, on OS X and iOS, that your environment variable
must not undergo NFC/NFD conversion, use QString::fromUtf8(qgetenv(x))
As a corollary, in cross-platform code that is not dealing with file paths, you
can choose either qgetenv or qEnvironmentVariable to suit your code best.
Note that if your variable contains numbers, you should use
qEnvironmentVariableIntValue:
C) qEnvironmentVariableIntValue
Use if you just want the value. Use it directly if an unset variable is
equivalent to it set to zero:
x = qEnvironmentVariableIntValue("FOO");
Do not write:
if (qEnvironmentVariableIsSet("FOO"))
x = qEnvironmentVariableIntValue("FOO");
write instead:
bool ok;
x = qEnvironmentVariableIntValue("FOO", &ok);
it's equivalent to:
x = qgetenv("FOO").toInt(&ok);
but won't allocate memory in a QByteArray temporary.
D) qEnvironmentVariableIsSet, qEnvironmentVariableIsEmpty
Prefer !qEnvironmentVariableIsEmpty over the IsSet alternative. This allows
"unsetting" a variable in a Unix shell by setting it to empty. Example:
$ QT_MESSAGE_PATTERN= ./appname
E) qputenv, qunsetenv
Don't use. They leak memory by construction. If you're dealing with the
environment for a child process, set it with QProcessEnvironment instead.
--
Thiago Macieira - thiago.macieira (AT) intel.com
Software Architect - Intel Open Source Technology Center
More information about the Development
mailing list