c++ - 我需要/如何释放 wstring、wstringstream、 vector

标签 c++ vector namespaces stringstream

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

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

任何有关优化此代码和/或进行内务处理的建议也值得赞赏。

#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++ 对象在删除时都会释放资源,包括内存。如果您需要更多控制,可以使用调整大小/保留功能来手动操作内存。您还可以将内存“移出”对象,使其生命周期比对象本身更长。
但是,默认情况下,C++ 将自行分配/释放内存(易于使用/难以误用)。

关于c++ - 我需要/如何释放 wstring、wstringstream、 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70788244/

相关文章:

c++ - 如何在 C++ 中为每个对象使用单独的构造函数参数动态分配对象数组?

c++ - 如何在 C++ 中访问命名空间中的类成员函数

python - 我该如何在python中出现名称错误

c++ - 传递 const int* 和 int* 时调用不同版本的重载函数 (const int* const&/&&)

c++ - 如何在与 C++ 中的派生类型匹配的元素上创建迭代器?

c++ - 将文本文件中的数据提取到结构中

c++ - multimap<vector<int>> ,char> 怎么排序呢?

找不到 PHP 命名空间类

c++ - 使用递归和回溯生成所有可能的组合

C++ - 返回 C++11 std::array