【问题标题】:Do I need to/How to free wstring, wstringstream, vector我需要/如何释放 wstring、wstringstream、向量
【发布时间】:2022-01-20 14:45:48
【问题描述】:

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

这个示例程序是为了展示代码。我使用 wstringstream、wstring 和向量,其中我有一个分隔字符串,我需要提取并处理列表中的每个项目。

任何有关优化此代码和/或做家务的建议都非常感谢。

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

【问题讨论】:

  • 除非你使用malloc/new,否则不需要free/delete。查找 RAII,因为提到的所有类型都是 RAII 类型,而漫画本身就是这样。
  • 请阅读this

标签: c++ vector namespaces stringstream


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多