0

前几天,我被告知(在 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 向量?

4

2 回答 2

4

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

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

于 2011-04-18T11:47:13.930 回答
1

使用最好的工具来完成这项工作。有些情况需要使用静态数组,有些情况需要使用动态数组。当情况需要动态数组时,请改用向量。

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));
于 2011-04-18T12:12:28.510 回答