[英]Equality-test std::string against char*, is operator==() always safe?
STL運算符和std::string
重載是否意味着可以安全地使用operator==
將char*
與std::string
進行比較,而沒有限制,即LHS / RHS?
不, 沒有限制是不安全的。 限制是:
char*
不能為空指針。 char*
指向的字符序列必須以零分隔(即以\\0
結尾) 但是,哪一個放在左邊和哪一個放在右邊並不重要-它給出相同的結果。
但有一個警告: std::string
s可能包含\\0
不在結尾的字符。 將其中一個與char*
字符序列進行比較將始終為false,因為比較將在char*
遇到的第一個\\0
處停止。
例:
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
可以包含多個空字符。 但是, std::string
和char*
operator==
定義為
將字符串的內容與另一個字符串或CharT的以null終止的數組進行比較。
該問題的示例:
std::string a = "hello";
char* b = "hello\0fellow\0";
bool equals = (a == b); // will give true, though a and b are not the same
如果您的char*
字符串不是空值終止,則可能會出現另一個問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.