Here is my working code. Do I need to clear or free wstring, wstringstream, vector in the func()? If so, how? I see there is a .clear() function for the vector and wstring and wstream.
This sample program is to show the code. I use the wstringstream, wstring, and vector where I have a delimited-string and I need to extract and act on each item in the list.
Any suggestions for optimizing this code and/or doing housekeeping is appreciated too.
#include <windows.h>
#include <strsafe.h>
#include <vector>
#include <sstream>
using namespace std;
void func()
{
WCHAR sComputersInGroup[200] = L"PC1|PC2|PC3|PC4|";
WCHAR sSN[200]{};
wstringstream wSS(sComputersInGroup);
wstring wOut;
vector<wstring> vComputer;
while (wSS.good())
{
getline(wSS, wOut, L'|');
vComputer.push_back(wOut);
}
INT i = 0;
while (i < (INT) vComputer.size())
{
if (vComputer[i].length() > 0)
{
StringCchCopy(sSN, 16, vComputer[i].c_str());
}
i ;
}
}
int main()
{
for (INT i=0;i<20000;i )
func();
}
CodePudding user response:
Most containers in C have two quantities. A size (how much it holds) and capacity (how much it already has allocated). vector::resize for example, changes the size, but will not alter the capacity unless required. vector::reserve changes the capacity, but the size.
By convention, all C objects free resources, including memory, when they are deleted. If you need more control, you can use the resize/reserve functions to manually manipulate memory. You can also "move" the memory out of the object to make it live longer than the object itself.
However, by default, C will allocate/free memory all by itself (easy to use/hard to misuse).
