前几天,我被告知(在 stackoverflow 上!)因为不使用向量而不是动态分配的 wchar 数组。
所以我研究了使用这种字符串操作方法,因为这似乎是防止可能的内存泄漏的好主意。
我想出的是,除非我错误地使用了向量模板类,否则使用向量比使用堆分配的数组和旧的 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 appdata\local 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 向量包含所有字符串的串联。相反,它只包含第一个插入的字符串。
另外,我想我记得听说过虽然不可能在初始化列表中分配向量的值,但它可能是 c++0x 的一个特性。这是正确的 - 是否有任何方法(目前)可以执行以下操作:
vector<wchar> sBleh = { _T("bleh") };
最后,对于我想通过上面的简单例程实现的目标,我会更好地使用动态分配的数组,还是应该坚持使用看似不灵活的 wchar 向量?