I have the following code in C++ on Win32. It's simply a C++ warp on some Win32 API that returns "CHAR *"
wstring expandEnvironmentVariables(const wstring & str)
{
DWORD neededSize = ExpandEnvironmentStrings(str.c_str(), nullptr, 0);
vector<WCHAR> expandedStr(neededSize);
if (0 == ExpandEnvironmentStrings(str.c_str(), expandedStr.data(), static_cast<DWORD>(expandedStr.size()))) {
return wstring(str);
}
return wstring(expandedStr.data());
}
What bothers me about this code, is the double copy of the result.
- by the API into a vector of WCHARs.
- from the vector into std::wstring.
Is there a way to implement this code with just a single copy, and without a major change to the signature of the function. This is a specific example, but I'm more interested in the general solution and the right way to work with std::wstring / std::string, because this pattern shows itself in many places in the code.
Aucun commentaire:
Enregistrer un commentaire