std::string 可以包含嵌入的空值吗?
对于常规 C 字符串,空字符 '\0'
表示数据结束。
std::string
怎么样,我可以有一个嵌入空字符的字符串吗?
For regular C strings, a null character '\0'
signifies the end of data.
What about std::string
, can I have a string with embedded null characters?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
是的,您可以在
std::string
中嵌入空值。示例:
注意:
std::string
的c_str()
成员始终会向返回的 char 缓冲区附加一个空字符;但是,std::string
的data()
成员可能会也可能不会将空字符附加到返回的 char 缓冲区。小心operator+=
需要注意的一件事是不要在RHS 上将
operator+=
与char*
一起使用。它只会累加到空字符为止。例如:
正确的方式:
存储二进制数据更常见的是使用std::vector
一般情况下,更常见的是使用
std::vector
来存储任意二进制数据。这可能更常见,因为
std::string
的data()
和c_str()
成员返回 const 指针,因此内存不可修改。使用 &buf.front() 您可以直接修改缓冲区的内容。Yes you can have embedded nulls in your
std::string
.Example:
Note:
std::string
'sc_str()
member will always append a null character to the returned char buffer; However,std::string
'sdata()
member may or may not append a null character to the returned char buffer.Be careful of operator+=
One thing to look out for is to not use
operator+=
with achar*
on the RHS. It will only add up until the null character.For example:
The correct way:
Storing binary data more common to use std::vector
Generally it's more common to use
std::vector
to store arbitrary binary data.It is probably more common since
std::string
'sdata()
andc_str()
members return const pointers so the memory is not modifiable. with &buf.front() you are free to modify the contents of the buffer directly.是的。 std::string 只是一个具有优点的
vector
。然而,在将这样的野兽传递给调用
.c_str()
并在 0 处停止的东西时要小心。Yes. A std::string is just a
vector<char>
with benefits.However, be careful about passing such a beast to something that calls
.c_str()
and stops at the 0.你可以,但你为什么要这么做?在 std::string 中嵌入 NUL 只会带来麻烦,因为传递 std::string 的函数很可能会使用它的 c_str() 成员,并且大多数人会假设第一个 NUL 指示字符串的结尾。因此,这不是一个好主意。另请注意,在 UTF-8 中,只有“\0”会导致 0,因此即使出于 i18n 目的,也没有理由嵌入 NUL。
You can, but why would you want to? Embedding NUL in an std::string is just asking for trouble, because functions to which you pass an std::string may very well use it's c_str() member, and most will assume that the first NUL indicates the end of the string. Hence this is not a good idea to do. Also note that in UTF-8, only '\0' will result in a 0, so even for i18n purposes, there is no justification for embedding NULs.
是的,这是有效的。
字符串中间可以有一个空字符。
但是,如果您使用中间带有空字符的 std::string 和 ac 字符串
在未定义行为小镇中发挥你的作用 - 没有人愿意在那里!!!:
Yep this is valid.
You can have a null character in the middle of the string.
However, if you use a std::string with a null character in the middle with a c string
function your in undefined behaviour town - and nobody wants to be there!!!: