簡體   English   中英

對char *進行相等測試std :: string,operator ==()始終安全嗎?

[英]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::stringchar* 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM