Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

In particular, how do the code check if memory for chars should be reallocated? Or how many chars the user entered? If I wanted to assign a C-string's value to my implementation of a string class 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;
    }

Easy enough. But the operator>> of the std::string is really making me curious.

like image 578
Anhil Avatar asked Sep 09 '26 07:09

Anhil


1 Answers

Fundamentally, the implementation looks something like this (ignoring the fact that both the streams and the string are templates):

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;
}

A reasonable implementation would probably use an algorithm which would process the content of the stream buffer's buffer segment-wise, e.g., to avoid the repeated checks and calls to is() (although for the std::ctype<char> it is really just applying a mask to an element of an array). In any case, the input operator wouldn't faff about allocating memory: a typical case "not my job".

like image 165
Dietmar Kühl Avatar answered Sep 13 '26 03:09

Dietmar Kühl