Usually when we write code, have you thought about the initiative to release the vector memory?
1, for the small amount of data vector, there is no need to voluntarily release the vector, everything to the operating system.
2, but for a large number of data vector, the data inside the vector is deleted, the initiative to release the vector memory becomes very necessary!
Readers can create a new console program, run the code to see the output, and look at the code:
[CPP]View PlainCopy
- #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); //Check memory condition at this time
- 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); //Check again at this time
- 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; At this time the capacity is 0
- Getcurprocessmemory (GetCurrentProcess (), wszworking, wszpeakworking); //Check memory
- Wcout << "working:" << wszworking.c_str () << "peakworking:" << wszpeakworking.c_str () << Endl;
- Wcout << "vector size:" << ary.size () << Endl; 0
- //getchar ();
- System ("pause");
- return 0;
- }
78500067
How does C + + quickly empty vectors and release vector memory?