简体   繁体   中英

Return std::string directly from char*

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?

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM