7

众所周知,C++11 的标准库允许轻松地将字符串从 UTF-8 编码转换为 UTF-16。但是,以下代码成功地转换了无效的 UTF-8 输入(至少在 MSVC2010 下):

#include <codecvt>
#include <locale>
#include <string>

int main() {
    std::string input = "\xEA\x8E\x97" "\xE0\xA8\x81" "\xED\xAE\x8D";
    std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t> converter;
    try {
        std::u16string output = converter.from_bytes(input.data());
        printf("Converted successfully\n");
    }
    catch(std::exception &e) {
        printf("Error: %s\n", e.what());
    }
}

这里的字符串包含 9 个字节,3 个代码点。最后一个代码点是 0xDB8D,它是无效的(适合代理项的范围)。

是否可以仅使用现代 C++ 标准库检查 UTF-8 字符串的完美有效性?在这里,我的意思是不允许维基百科文章中描述的所有无效案例。

4

0 回答 0