[Interest] Is it safe to use QString::utf16() as a Windows wchar_t*?

Nikos Chantziaras realnc at gmail.com
Fri Nov 10 10:00:51 CET 2017


On 10/11/17 00:07, André Pönitz wrote:
> On Thu, Nov 09, 2017 at 11:15:28AM +0200, Nikos Chantziaras wrote:
>> On Windows, I use this:
>>
>>    void func(const wchar_t*);
>>    QString s;
>>
>>    // ...
>>
>>    func(reinterpret_cast<const wchar_t*>(s.utf16()));
>>
>> This saves an allocation, a copy and a free since I don't have to use
>> QString::toWCharArray(). However, is this actually safe? "It seems to work,"
>> and AFAIK, QString::d->data() is already in the format and encoding Windows
>> excepts a wchar_t* to be. Is this correct?
> 
> As others indicated, yes, it's safe, under the conditions you specified.
> 
> Whether it makes sense to sacrifice e.g. platform independence in user
> code for one saved string copy is a different question, very likely
> with a different answer.

This is Windows-only code within an #ifdef block. The QString doesn't 
exist when building for other platforms. So you know, if it's shorter 
code and more efficient (as a bonus), then why not.




More information about the Interest mailing list