why std::string is not implicitly converted to bool

前端 未结 4 1325
暖寄归人
暖寄归人 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-18 23:55

    std::string still has to coexist with C-style strings.

    A C-style string is by definition "a contiguous sequence of characters terminated by and including the first null character", and is generally accessed via a pointer to its first character. An expression such as "hello, world" is, in most contexts, implicitly converted to a pointer to the first character. Such a pointer may then be implicitly converted to bool, yielding true if the pointer is non-null, false if it's null. (In C, it's not converted to bool, but it can still be used directly as a condition, so the effect is nearly the same.)

    So, due to C++'s C heritage, if you write:

    if ("") { ... }
    

    the empty string is already treated as true, and that couldn't easily be changed without breaking C compatibility.

    I suggest that having a C-style empty string evaluate as true and a C++ empty std::string evaluate as false would be too confusing.

    And writing if (!s.empty()) isn't that difficult (and IMHO it's more legible).

提交回复
热议问题