Tho*_*ard 8 c++ linux stdstring
我有一个struct
看起来像这样:
struct queue_item_t {
int id;
int size;
std::string content;
};
Run Code Online (Sandbox Code Playgroud)
我有一个std::vector< queue_item_t >
从数据库查询中填充了许多这些.
处理每个项目时,将从磁盘读取文件,并将其内容放入content
字符串成员中.该项目被处理(content
被解析),我.clear()
在字符串上执行,以免占用我的所有记忆.
但是,这似乎并没有释放内存.我有数十万个项目正在处理中,最终,内存使用量将超出可用范围,并且应用程序被Linux以"内存不足"为原因杀死.
如何释放这些字符串使用的内存?
bob*_*bah 15
std :: string和std :: vector不会在clear()中更改容器容量(=>不释放容器内存).只要需要压缩,就应该使用下面的临时对象技巧(通常不需要).
my_queue_item.content.clear(); // clear
std::string(my_queue_item.content).swap(my_queue_item.content); // compact
Run Code Online (Sandbox Code Playgroud)
当需要清理+压缩时,可以使上面的代码更简单:
std::string().swap(my_queue_item.content);
Run Code Online (Sandbox Code Playgroud)
一些字符串实现是copy-on-write.当从多个地方引用时,这样的字符串将在写入时重新分配存储器.
归档时间: |
|
查看次数: |
6723 次 |
最近记录: |