How is std :: cin >> std :: string implemented?

In particular, how does the code check if memory should be reallocated for characters? Or how many characters does the user enter? If I wanted to assign the value of string C to my string class implementation, I would probably do something like this

   String& operator=(String& to, const char *from)
   {
      if((strlen(from) + 1) > to.size) {
        if (to.str != NULL) {
          delete[] to.str;
          to.str = NULL;
        }
        to.size = strlen(from) + 1;
        to.str = new char[to.size];
      }
      strcpy(to.str, from);
      return to;
    }

Simple enough. But the → operator from std :: string really arouses my interest.

+4
source share
2 answers

In essence, the implementation looks something like this (ignoring the fact that both threads and string are patterns):

std::istream& operator>> (std::istream& in, std::string& value) {
    std::istream::sentry cerberos(in);
    if (cerberos) {
        value.erase();
        std::istreambuf_iterator<char> it(in), end;
        if (it != end) {
            std::ctype<char> const& ctype(std::use_facet<std::ctype<char> >(in.getloc()));
            std::back_insert_iterator<std::string> to(value);
            std::streamsize n(0), width(in.width()? in.width(): std::string::max_size());
            for (; it != end && n != width && !ctype.is(std::ctype_base::space, *it); ++it, ++to) {
                *to = *it;
            }
        }
    }
    else {
        in.setstate(std::ios_base::failbit);
    }
    return in;
}

, , , , , is() ( std::ctype<char> ). , : " ".

+4

, - . c, realloc. , stl realloc, .

, string typedef 'd : std::basic_string<char>, char. , , . , , , , .

std::cin >> std::string, for, char

0

All Articles