使用矢量<wchar>而不是动态分配的 WCHAR 数组

use vector<wchar> instead of dynamically allocated wchar array

本文关键字:数组 动态分配 WCHAR wchar lt gt      更新时间:2023-10-16

前几天,我被告知(在stackoverflow!)不使用vector而不是动态分配的wchar数组。

因此,我研究了使用这种字符串操作方法,因为它似乎是防止可能的内存泄漏的好主意。

我想到的是,除非我使用vector模板类不正确,否则使用vector要比使用堆分配数组和老式memcpy灵活得多。

#include <shlobj.h>
HRESULT ModifyTheme()
{
using namespace std;
vector <WCHAR>  sOutput;
vector <WCHAR>  sPath;      
vector <WCHAR>  sThemesLocation;
vector <WCHAR>  sThemeName; 
const WCHAR sThemesPath []  = _T("\Microsoft\Windows\Themes");
const WCHAR sFileName []    = _T("\darkblue.theme");
sOutput.resize(MAX_PATH);
sPath.resize( MAX_PATH );   
sThemesLocation.resize( MAX_PATH );
sThemeName.resize( MAX_PATH );
// Get appdatalocal folder
SHGetFolderPath(NULL, CSIDL_LOCAL_APPDATA, NULL, 0, &sPath[0] );
// copy consts to vectors   
memcpy( &sThemesLocation[0],    sThemesPath,    sizeof(sThemesPath) );
memcpy( &sThemeName[0],         sFileName,      sizeof(sFileName) );    
// append themes path & filename
sOutput.insert( sOutput.begin(), sPath.begin(), sPath.end() );
sOutput.insert( sOutput.end()-1, sThemesLocation.begin(), sThemesLocation.end() );
sOutput.insert( sOutput.end()-1, sThemeName.begin(), sThemeName.end() );    
wcout << &sThemeName[0] << endl;
wcout << &sThemesLocation[0] << endl;
wcout << &sPath[0] << endl;
wcout << &sOutput[0] << endl;
return S_OK;
}

我希望sOutput向量包含所有字符串的连接。相反,它只包含第一个插入的字符串。

另外,我记得我听说过,虽然不能在初始化列表中为vector赋值,但这可能是c++0x的一个特性。这是正确的吗?(目前)是否有办法做到以下几点:

vector<wchar> sBleh = { _T("bleh") };

最后,对于我想用上面的简单例程实现的目标,我是应该使用动态分配的数组更好,还是应该坚持使用看似不灵活的wchar向量?

如果你使用std::vector<WCHAR>,你可能应该使用std::wstring,因为它也是WCHAR元素的容器。

以下链接可能对您有所帮助:
std::wstring (typepedef of std::basic_string<WCHAR>)
std:: basic_string

使用最好的工具。有些情况需要使用静态数组,有些情况需要使用动态数组。当需要使用动态数组时,请使用vector。

Mark Ingram是正确的,你可以使用wstring,但只有当wchar_t与WCHAR大小相同时。

像这样的东西更适合您的需要(注意,我没有通过编译器运行下面的代码,因为有太多Microsoft特定的结构。):

WCHAR sPath[MAX_PATH]; // doesn't need to be a dynamic array, so don't bother with a vector.
SHGetFolderPath(NULL, CSIDL_LOCAL_APPDATA, NULL, 0, &sPath[0] );
const WCHAR sThemesPath[] = _T("\Microsoft\Windows\Themes"); // doesn't need to be a dynamic array, so don't bother with a vector.
const WCHAR sFileName[] = _T("\darkblue.theme"); // doesn't need to be a dynamic array, so don't bother with a vector.
vector<WCHAR> sOutput; // this needs to be dynamic so use a vector.
// wcslen should probably be replaced with an MS specific call that gets the length of a WCHAR string
copy(sPath, sPath + wcslen(sPath), back_inserter(sOutput));
copy(sThemesPath, sThemesPath + wcslen(sThemesPath), back_inserter(sOutput));
copy(sFlieName, sFileName + wcslen(sFileName), back_inserter(sOutput));