对char *进行相等测试std :: string,operator ==()始终安全吗? [英] Equality-test std::string against char*, is operator==() always safe?
问题描述
std :: string
的STL运算符和重载是否意味着使用 operator ==
比较 char *
是安全的针对 std :: string
,不受限制,这是LHS/RHS?
Do the STL operators and overloads for std::string
mean that it is safe to use operator==
to compare a char*
against a std::string
, without restriction which is the LHS/RHS?
推荐答案
不,不受限制是不安全的.限制为:
No, it is not safe without restrictions. The restrictions are:
-
char *
不能为空指针. -
char *
指向的字符序列必须以零定界(即以\ 0
结尾)
- the
char*
must not be a nullpointer. - the character sequence pointed to by the
char*
has to be zero-delimited (i.e. end with a\0
)
但是,哪一个放在左边和哪一个放在右边并不重要-它给出相同的结果.
But it is not important which one you put left and which one right - it gives the same result.
但是有一个警告: std :: string
s可能包含 \ 0
个不在结尾的字符.将其中一个与 char *
字符序列进行比较将始终为false,因为比较将在 char *
\ 0 处停止>.
But there's a caveat: std::string
s may contain \0
characters that are not at the end. 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 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 *进行相等测试std :: string,operator ==()始终安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!