[英]Equality-test std::string against char*, is operator==() always safe?
STL运算符和std::string
重载是否意味着可以安全地使用operator==
将char*
与std::string
进行比较,而没有限制,即LHS / RHS?
No, it is not safe without restrictions . 不, 没有限制是不安全的。 The restrictions are:
限制是:
char*
must not be a nullpointer. char*
不能为空指针。 char*
has to be zero-delimited (ie end with a \\0
) char*
指向的字符序列必须以零分隔(即以\\0
结尾) But it is not important which one you put left and which one right - it gives the same result. 但是,哪一个放在左边和哪一个放在右边并不重要-它给出相同的结果。
But there's a caveat: std::string
s may contain \\0
characters that are not at the end. 但有一个警告:
std::string
s可能包含\\0
不在结尾的字符。 Comparing one of those against a char*
character sequence will always give false, because the comparison will stop at the first \\0
encountered in the char*
. 将其中一个与
char*
字符序列进行比较将始终为false,因为比较将在char*
遇到的第一个\\0
处停止。
Example: 例:
char c[] = "Hello\0 World!";
std::string s(c, sizeof(c));
std::cout << ((s == c) ? "ok" : "meh") << '\n'; //meh - compares only until the first \0
std::cout << c << '\n'; //Hello - cout also stops at first \0
std::cout << s << '\n'; //Hello World!
是的,只要您确定char *不是空指针,并且它以空终止,就可以安全使用。
A std::string
can contain multiple null characters. 一个
std::string
可以包含多个空字符。 However operator==
for std::string
and char*
is defined as 但是,
std::string
和char*
operator==
定义为
Compares the contents of a string with another string or a null-terminated array of CharT.
将字符串的内容与另一个字符串或CharT的以null终止的数组进行比较。
Example of that problem: 该问题的示例:
std::string a = "hello";
char* b = "hello\0fellow\0";
bool equals = (a == b); // will give true, though a and b are not the same
Another issue may arise if you char*
string is not null-terminated. 如果您的
char*
字符串不是空值终止,则可能会出现另一个问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.