c++string

C++ strlen for the String class


How does the C++ length() method work for the std::string class?


Solution

  • The std::string class has several constructors, including one that takes both a const char* raw C string and a size_t length, and another that takes just a const char* raw C string. For the former, the provided length is stored, and for the latter, the length is computed once by invoking strlen or by performing an equivalent computation. Calling std::string::length()const just returns the previously computed value. It is not recomputed each time it is invoked.