Inconsistency between std::string and string literals

后端 未结 6 1454
耶瑟儿~
耶瑟儿~ 2020-12-28 12:30

I have discovered a disturbing inconsistency between std::string and string literals in C++0x:

#include 
#include          


        
6条回答
  •  攒了一身酷
    2020-12-28 13:18

    However, I think this is very undesirable: surely std::string and string literals should behave the same when it comes to properties as basic as their length?

    String literals by definition have a (hidden) null character at the end of the string. Std::strings do not. Because std::strings have a length, that null character is a bit superfluous. The standard section on the string library explicitly allows non-null terminated strings.

    Edit
    I don't think I've ever given a more controversial answer in the sense of a huge amount of upvotes and a huge amount of downvotes.

    The auto iterator when applied to a C-style array iterates over each element of the array. The determination of the range is made at compile-time, not run time. This is ill-formed, for instance:

    char * str;
    for (auto c : str) {
       do_something_with (c);
    }
    

    Some people use arrays of type char to hold arbitrary data. Yes, it is an old-style C way of thinking, and perhaps they should have used a C++-style std::array, but the construct is quite valid and quite useful. Those people would be rather upset if their auto iterator over a char buffer[1024]; stopped at element 15 just because that element happens to have the same value as the null character. An auto iterator over a Type buffer[1024]; will run all the way to the end. What makes a char array so worthy of a completely different implementation?

    Note that if you want the auto iterator over a character array to stop early there is an easy mechanism to do that: Add a if (c == '0') break; statement to the body of your loop.

    Bottom line: There is no inconsistency here. The auto iterator over a char[] array is consistent with how auto iterator work any other C-style array.

提交回复
热议问题