2

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();
}
JeffR
  • 765
  • 2
  • 8
  • 23
  • 1
    Unless you use `malloc`/`new`, there is no need to `free`/`delete`. Look up RAII, as all of the types mentioned are RAII types, and manga that stuff themselves. – NathanOliver Jan 20 '22 at 14:53
  • Please read [this](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-i-e-while-stream-eof-cons). – n. m. could be an AI Jan 20 '22 at 15:01

1 Answers1

2

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).

Tiger4Hire
  • 1,065
  • 5
  • 11