简体   繁体   English

直接从 char* 返回 std::string

[英]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.我正在构建一个跨平台应用程序,我有一个将平台字符类型转换为 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然后,对于 Windows 上的实现,我会分配一个新字符串,调用

WideCharToMultibyte

However, for the implementation on macos, I would just like to return the original string.但是,对于macos上的实现,我只想返回原始字符串。 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.但是,问题是,当我在chars上调用std::string构造函数时,它必须复制字符。 How can I avoid this?我怎样才能避免这种情况?

For purely ASCII texts, you can create it as stated here :对于纯 ASCII 文本,您可以按照此处所述进行创建:

std::string ensureUtf8(platChar* chars)
{
#if _WIN32
    wstring ws(chars);
    return std::string(ws.begin(), ws.end());
#else
    return std::string(chars);
#endif
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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