why std::string is not implicitly converted to bool

前端 未结 4 1311
暖寄归人
暖寄归人 2021-02-18 23:35

Is there a reason why in c++ std::string is not implicitly converted to bool? For example

std::string s = \"\"
if (s) { /* s in not empty */ }
         


        
4条回答
  •  无人及你
    2021-02-19 00:18

    This article mentions some reasons why operator bool() can lead to surprising results.

    Note that std::string is just a typedef for std::basic_string. There is also std::wstring for multi-byte characters. An implicit conversion would let you write:

    std::string foo = "foo";
    std::wstring bar = "bar";
    if (foo == bar) {
      std::cout << "This will be printed, because both are true!\n";
    }
    

提交回复
热议问题