I want to pass a QString variable to a function with const wchar_t* argument.
Safe solution is:
void foo(const wchar_t*);
QString x = "test";
foo(x.toStdWString().c_str());
but it has overhead of converting to wstring. Is there any faster solution?
How about this solution? Is it safe and portable?
foo(reinterpret_cast<const wchar_t*>(x.constData()));
No, the reinterpret cast is not safe and will not work on some platforms where the encoding is different. QChar is 16-bit and the internal encoding is UTF-16, but on Linux wchar_t is 32-bit UCS-4 encoding.
The cast would happen to work (it's still undefined behaviour, but msc++ does not currently do anything that would break it) on Windows where wchar_t is forever stuck at 16 bit, but the point of using Qt is being portable, right?
Note, that the conversion via std::wstring is as efficient as you can get. Given the difference in encoding memory has to be allocated once, which is managed by the std::wstring (the return copy can be elided even in C++98) and std::wstring::c_str() is a trivial getter.
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