有人可以解释这个c ++代码的区别吗?

问题描述 投票:0回答:1

我不能确切地说出这些之间的有效区别,第一个似乎更有效地工作。第二个适用于调整,但是有不完整的多字节字符串的问题,当我删除resize bytesWritten - 1时,它根本不起作用。我很想知道为什么这些工作方式不同。谢谢!

第一:

size_t maxBytes = JSStringGetMaximumUTF8CStringSize(str);
std::vector<char> buffer(maxBytes);
JSStringGetUTF8CString(str, buffer.data(), maxBytes);
return std::string(buffer.data());

第二:

std::string result;
size_t maxBytes = JSStringGetMaximumUTF8CStringSize(str);
result.resize(maxBytes);
size_t bytesWritten = JSStringGetUTF8CString(str, &result[0], maxBytes);
// JSStringGetUTF8CString writes the null terminator, so we want to resize
// to `bytesWritten - 1` so that `result` has the correct length.
result.resize(bytesWritten - 1);
return result;
c++ std javascriptcore
1个回答
1
投票

std::string的字符数组是不合法的,不是通过c_str(),而不是通过data()(至少在C ++ 17之前),特别是不要像你那样获取第一个元素的地址。这就是区别,在第一个使用std::vector<char>的地方允许所有这些东西,第二个代码只是未定义的行为。它与javascript core btw无关。

© www.soinside.com 2019 - 2024. All rights reserved.