我有一个需要读写大文件的项目。
我决定使用ifstream::read()一次性将这些文件读入内存中的std::string中。 (这似乎是在c++中最快的方法:http://insanecoding.blogspot.com/2011/11/how-to-read-in-file-in-c.html和 http://insanecoding.blogspot.com/2011/11/reading-in-entire-file-at-once-in-c.html)
当切换文件时,我需要“重置”用作先前内存缓冲区的std::string(即,擦除char[]缓冲区以释放内存)。
我尝试过:
我决定使用ifstream::read()一次性将这些文件读入内存中的std::string中。 (这似乎是在c++中最快的方法:http://insanecoding.blogspot.com/2011/11/how-to-read-in-file-in-c.html和 http://insanecoding.blogspot.com/2011/11/reading-in-entire-file-at-once-in-c.html)
当切换文件时,我需要“重置”用作先前内存缓冲区的std::string(即,擦除char[]缓冲区以释放内存)。
我尝试过:
std::string::clear()
std::string::assign("")
std::string::erase(0, std::string::npos)
std::string::resize(0)
std::string::reserve(0)
但是,在Visual Studio 2008下,这样不会释放std::string中使用的内存:其基础缓冲区不会被释放。
我发现唯一的方式是调用std::string::swap(std::string("")), 强制在实际std::string和参数中的空字符串之间更改内部缓冲区,从而删除它。
我觉得这个行为有点奇怪...
我只测试过Visual Studio 2008,不知道这是STL标准行为还是仅适用于MSVC。
你能给我一些线索吗?
std::string
读取文件远非最优方式。 - user405725shrink_to_fit()
方法来发起一个非绑定请求以进行内存释放。 - Kerrek SBshrink_to_fit
,根据C++11 §21.4.4/14,“它是将capacity()减少到size()的非约束性请求。[注意:该请求是非约束性的,以允许实现特定的优化。—end note]”。祝好运! - Cheers and hth. - Alf