0

I'm building a cross platform application, and I have a function which converts the platform character type into UTF-8.

#if _WIN32
typedef wchar_t platChar;
#else
typedef char platChar;
#endif

std::string ensureUtf8(platChar* chars);

Then, for the implementation on windows I would allocate a new string, call

WideCharToMultibyte

However, for the implementation on macos, I would just like to return the original string. If I do this:

std::string ensureUtf8(platChar* chars)
{
    return std::string(chars);
}

However, the issue is, when I call std::string constructor on chars, it must copy chars. How can I avoid this?

ManUser123
  • 41
  • 1
  • 5
  • 1
    You can't avoid this. `std::string` does not work this way. `std::string` owns its contents, so when constructed it always copies the character string that was used to construct it, into its own internal storage. You might be able to do something with `std::string_view` from C++17. – Sam Varshavchik Nov 12 '20 at 01:05
  • @SamVarshavchik The thing is, I need to be able to release the memory automatically so I can't really do that with `std::string_view` – ManUser123 Nov 12 '20 at 01:10
  • Well, that means there's nothing you can do. `std::string` doesn't work this way. Perhaps you should try asking the real problem you're trying to solve. No, not the one of constructing std::string directly from a char *, but the problem to which the solution you believe involves constructing a std::string from a char * so that's what you're asking about. Perhaps if you ask your real question you'll find out there's a better way to do this, in some different fashion. – Sam Varshavchik Nov 12 '20 at 01:13
  • i guess you're right – ManUser123 Nov 12 '20 at 01:19
  • I don't understand the question... It seems pretty obvious that the INPUT string has a character width depending on the OS. The output string should always be encoded in UTF-8. UTF-8 strings are always stored in single-byte char strings. – Michaël Roy Nov 12 '20 at 01:46

1 Answers1

0

For purely ASCII texts, you can create it as stated here:

std::string ensureUtf8(platChar* chars)
{
#if _WIN32
    wstring ws(chars);
    return std::string(ws.begin(), ws.end());
#else
    return std::string(chars);
#endif
}
Victor
  • 460
  • 3
  • 11
  • Does your answer differ or enhance the duplicate answer that you link to? I don't mind enhancements at all - but sometimes, a link as a comment is just enough. – Ted Lyngmo Nov 12 '20 at 03:59
  • I don't think you understood what my question was. I probably should've stated it clearer. My question was how to avoid copying `chars` when it's not win32. – ManUser123 Nov 12 '20 at 04:33