Important: Please read the Qt Code of Conduct -

From wchar_t* to QString: QString::fromUtf16 or QString::fromWCharArray?

  • Today, my CppDepend complained about the following code:

    wchar_t* buffer = _wgetenv(L"USERNAME");
    if (buffer != NULL)
        userId = QString::fromUtf16(buffer).toLower();

    The problem is that buffer is wchar_t*, while QString::fromUtf16 expects a const ushort *.

    As I wasn't quite sure whether to replace the fromUtf16 function call with

    userId = QString::fromUtf16(reinterpret_cast<const ushort*>(buffer)).toLower();

    or with

    userId = QString::fromWCharArray(buffer).toLower();

    I wrote this little test program:

    On Linux, wchar_t seems to be 4 bytes and there seems to be a difference between the two functions:

    sizeof(wchar_t) =  4 
    QString::fromUtf16(reinterpret_cast<const ushort*>(text)) => "F" 
    QString::fromWCharArray(text) => "FooBar"

    on Windows, wchar_t seems to be 2 bytes and there seems to be no difference:

    sizeof(wchar_t) =  2 
    QString::fromUtf16(reinterpret_cast<const ushort*>(text)) => "FooBar" 
    QString::fromWCharArray(text) => "FooBar"

    My conclusion would be that in this case, where I have to create a QString out of a wchar_t*, the safest and most portable way is to use QString::fromWCharArray(text). Is my conclusion correct, or am I overlooking something?

    Kind regards,