简体   繁体   中英

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:

  • the char* must not be a nullpointer.
  • the character sequence pointed to by the char* has to be zero-delimited (ie end with a \\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. 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* .

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. However operator== for std::string and char* is defined as

Compares the contents of a string with another string or a null-terminated array of CharT.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM