1

请参阅下面的代码:

void foo() {
  std::ifstream f("data");
  string line;
  vector<string> r;
  while(getline(f, line)) {
    r.push_back(line);
  }
  f.close();
  r.resize(0);
}

int main(int argc, char *argv[])
{
  foo();
  cout << "load done" << endl;
  while(1) {;}
  return 0;
}

我使用 while(1) 循环来检查htop工具中的内存使用情况, r 可能使用 5GB RES,但load done打印后RES仍然需要 5GB。有什么问题?

4

2 回答 2

2

Resize doesn't guarantee that the underlying memory will be freed.

You should try with shrink_to_fit, which will reduce the capacity of the contained to fit its size.

于 2014-11-24T10:38:18.980 回答
0

我认为 vector klass 的擦除和/或清除功能会为您做到这一点。cpusplus.com上还有一个非常好的矢量文档

于 2014-11-24T11:59:56.097 回答