0

Why does the following code from this answer work:

QString username = "Bond";
std::wstring username = username.toStdWString();
PCWSTR username = username.c_str();

When the following does not:

QString username = "Bond";
PCWSTR username = username.toStdWString().c_str();
Jez
  • 175
  • 1
  • 1
  • 10

2 Answers2

0

The temporary object gets destroyed, the result of the c_str() is invalid after that point.

rpress
  • 462
  • 3
  • 6
0

The answer by rpress is of course correct. I am however using this conversion:

const QString usernameStr = "Bond";
auto usernameStrPtr = reinterpret_cast<PCWSTR>(usernameStr.utf16());

In most cases this will avoid one unnecessary allocation and conversion to std:wstring. I assume your expected coding is UTF16 anyway...

  • That one unecessary allocation is precisely what I was trying to avoid when I stumbled upon this problem, so this is a helpful way of doing it – Jez Aug 10 '21 at 14:31