怎么是std :: cin>> std :: string实现了吗?

时间:2013-10-22 23:21:49

标签: c++ string std cin stdstring

特别是,代码如何检查是否应该重新分配字符的内存?或者用户输入了多少个字符? 如果我想将C字符串的值赋给我的字符串类实现,我可能会做这样的事情

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

够容易。但运营商>> std :: string真的让我很好奇。

2 个答案:

答案 0 :(得分:4)

从根本上说,实现看起来像这样(忽略了流和字符串都是模板的事实):

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>它实际上只是将掩码应用于数组的元素)。在任何情况下,输入操作员都不会考虑分配内存:典型的情况是“不是我的工作”。

答案 1 :(得分:0)

我认为它必须使用某种智能内存分配管理。如果你熟悉c,你会看到函数realloc。我的想法是,stl中的大多数容器类在内部使用某种形式的realloc来为自己分配更多的内存。

要回答你的问题,字符串类是typedef来自另一个类:std::basic_string<char>,它基本上是一个char数组。因此,在内部它保留了可以根据用户的偏好或需求增长或缩小的内存。就像我之前提到的那样,内存管理是以最佳和安全的方式完成的,这样信息就不会丢失。

如果我要实现std::cin >> std::string,它将采用for循环的形式,遍历char数组并为数组中的每个字符赋值

相关问题