这是我的工作代码。我需要在 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/