平时我们在写代码时候,有思考过要主动去释放vector的内存吗?
1、对于数据量不大的vector,没有必要自己主动释放vector,一切都交给操作系统。
2、但是对于大量数据的vector,在vector里面的数据被删除后,主动去释放vector的内存就变得很有必要了!
读者可以新建一个控制台程序,把代码运行起来看输出,且看代码:
- #include <iostream>
- #include <vector>
- #include <string>
- #include <Windows.h>
- #include <Psapi.h>
- #pragma comment(lib, "Psapi.lib")
- using namespace std;
- //GetCurPorcessMemory
- bool GetCurProcessMemory(HANDLE handle, std::wstring& workingSize, std::wstring& peakWorkingSize)
- {
- //HANDLE handle = GetCurrentProcess();
- PROCESS_MEMORY_COUNTERS pmc;
- if (GetProcessMemoryInfo(handle, &pmc, sizeof(pmc)))
- {
- int size = pmc.WorkingSetSize/1024;
- wchar_t buf[10] = {0};
- _ltow(size, buf, 10);
- workingSize = std::wstring(buf);
- size = pmc.PeakWorkingSetSize/1024;
- _ltow(size, buf, 10);
- peakWorkingSize = std::wstring(buf);
- return true;
- }
- return false;
- }
- int _tmain(int argc, _TCHAR* argv[])
- {
- std::wstring wszWorking, wszPeakWorking;
- vector<string> ary;
- for (int i=0; i<1000000; i++)
- {
- ary.push_back("hello vector");
- }
- wchar_t wch;
- wcin >> wch;
- GetCurProcessMemory(GetCurrentProcess(), wszWorking, wszPeakWorking);// 此时检查内存情况
- wcout << "Working : " << wszWorking.c_str() << " PeakWorking : " << wszPeakWorking.c_str() << endl;
- wcin >> wch;
- //
- ary.clear();
- wcout << "vector clear" << endl;
- wcout << "vector capacity " << ary.capacity() << endl;
- GetCurProcessMemory(GetCurrentProcess(), wszWorking, wszPeakWorking);// 此时再次检查
- wcout << "Working : " << wszWorking.c_str() << " PeakWorking : " << wszPeakWorking.c_str() << endl;
- wcin >> wch;
- //vector<string>(ary).swap(ary);
- ary.swap(vector<string>(ary));
- wcout << "vector swap" << endl;
- wcout << "vector capacity " << ary.capacity() << endl;// 此时容量为0
- GetCurProcessMemory(GetCurrentProcess(), wszWorking, wszPeakWorking);// 检查内存
- wcout << "Working : " << wszWorking.c_str() << " PeakWorking : " << wszPeakWorking.c_str() << endl;
- wcout << "vector size : " << ary.size() << endl;//0
- //getchar();
- system("pause");
- return 0;
- }
https://blog.csdn.net/hellokandy/article/details/78500067