前几天,我被责备了(在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看似不灵活的向量?
发布于 2011-04-18 19:47:14
如果您使用的是std::vector<WCHAR>,那么您可能应该使用std::wstring,因为它也是WCHAR元素的容器。
以下链接可能会对您有所帮助:
std::wstring (std::basic_string<WCHAR>的类型定义)
std::basic_string
发布于 2011-04-18 20:12:29
使用最好的工具来完成这项工作。有些情况下需要使用静态数组,有些情况下需要使用动态数组。当情况需要动态数组时,请改用向量。
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));https://stackoverflow.com/questions/5702318
复制相似问题