【发布时间】:2010-10-18 21:49:21
【问题描述】:
我在我的程序中处理了很多字符串。 这些字符串数据在读入我的程序后的整个生命周期都不会改变。
但是由于 C++ 字符串保留了容量,它们浪费了很多肯定不会被使用的空间。 我试图释放这些空间,但没有成功。
以下是我试过的简单代码:
string temp = "1234567890123456";
string str;
cout << str.capacity() << endl;
str.reserve(16);
cout << str.capacity() << endl;
// capacity is 31 on my computer
str += temp;
cout << str.capacity() << endl;
str.reserve(16);
cout << str.capacity() << endl;
// can't release. The capacity is still 31.
(编译器为Visual C++)
我怎样才能释放它?
【问题讨论】:
-
你的内存真的用完了吗?如果不是,这是过早的优化。如果您的内存已用完,那么哪些对象实际上支配了您的内存分配?关键是这种事情没有帮助。
-
没有办法强制分配器使用更少的字节用于给定字符串的初始构造 -- 至少在不编写您自己的 STL 分配器类模板(和那时可能还没有)。
标签: c++ string visual-c++ memory-management