使用 WinAPI 时,您经常会遇到一些获取 LPWSTR 或 LPSTR 作为参数的方法。有时这个指针实际上应该是指向缓冲区的指针,例如:
int GetWindowTextW(HWND hWnd, LPWSTR lpString, int nMaxCount);
使用是一个好主意吗std::wstring
对于这样的缓冲区,在特殊情况下我强烈需要生成std::wstring
结果,无法将其替换为vector<wchar_t>
例如?
std::wstring myWrapper(HWND hWnd){
auto desiredBufferSize = GetWindowTextLengthW(hWnd);
std::wstring resultWstr;
resultWstr.resize(desiredBufferSize);
auto ret = GetWindowText(hWnd,
const_cast<wchar_t*>(resultWstr.data()), // const_cast
resultWstr.size());
// handle return code code
return resultWstr;
}
Both data()
and c_str()
string方法返回const指针,所以我们必须使用const_cast
消除常量,这有时是一个坏兆头。在这种情况下这是一个好主意吗?我可以做得更好吗?
使用字符串作为 C 字符串
自动类型转换自const char*
to std::string
,但反之亦然。
字符“\0”对于 std::string 来说并不特殊。
确保字符串大小(不仅仅是容量)足够大,适合 C 风格编写。
仅在下次调用非常量方法之前有效。
代码示例:
const int MAX_BUFFER_SIZE = 30; // Including NULL terminator.
string s(MAX_BUFFER_SIZE, '\0'); // Allocate enough space, NULL terminated
strcpy(&s[0], "This is source string."); // Write, C++11 only (VS2010 OK)
printf("C str: '%s'\n", s.c_str()); // Read only: Use const whenever possible.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)