Yes you can have embedded nulls in your std::string
.
Example:
std::string s;
s.push_back('');
s.push_back('a');
assert(s.length() == 2);
Note: std::string
's c_str()
member will always append a null character to the returned char buffer; However, std::string
's data()
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 a char*
on the RHS. It will only add up until the null character.
For example:
std::string s = "hello";
s += "world";
assert(s.length() == 5);
The correct way:
std::string s = "hello";
s += std::string("world", 6);
assert(s.length() == 11);
Storing binary data more common to use std::vector
Generally it's more common to use std::vector
to store arbitrary binary data.
std::vector<char> buf;
buf.resize(1024);
char *p = &buf.front();
It is probably more common since std::string
's data()
and c_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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…