我需要 to/How 来释放 wstring、wstringstream、vector

Do I need to/How to free wstring, wstringstream, vector

这是我的工作代码。我是否需要清除或释放 func() 中的 wstring、wstringstream、vector?如果是这样,如何?我看到向量和 wstring 和 wstream 有一个 .clear() 函数。

此示例程序用于显示代码。我使用 wstringstream、wstring 和 vector,其中我有一个分隔字符串,我需要提取列表中的每个项目并对其进行操作。

任何关于优化此代码的建议 and/or 做内务管理也非常感谢。

#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();
}

大多数 C++ 容器都有两个数量。大小(它拥有多少)和容量(它已经分配了多少)。 vector::resize 例如,更改大小,但除非需要,否则不会更改容量。 vector::reserve 更改容量,但更改大小。
按照惯例,所有 C++ 对象在删除时都会释放资源,包括内存。如果需要更多控制,可以使用 resize/reserve 函数手动操作内存。您还可以将内存“移”出对象,使其比对象本身的寿命更长。
但是,默认情况下,C++ 将 allocate/free 内存全部自行使用(容易 use/hard 误用)。