[英]c++, Win32 LoadString wrapper
i would like to have your opinion about this wrapper for LoadString Win32 function. 我想对LoadString Win32函数的此包装程序有您的意见。
int LoadWString( HINSTANCE hInstance_In, UINT uID_In, std::wstring &str_Out ){
return LoadStringW( hInstance_In, uID_In, (LPWSTR)str_Out.c_str(), (int)str_Out.max_size());
}
as it seems to work as expected, question is more about using strings max_size property as buffer size, does this have some negative drawbacks? 正如预期的那样,问题更多是关于使用字符串max_size属性作为缓冲区大小,这是否有一些负面的缺点?
c_str()
returns a non-modifiable pointer. c_str()
返回一个不可修改的指针。 It must not be written to. 不得写入。 Casting away const-ness and writing to the controlled sequence results in undefined behavior .
抛弃常数并写入受控序列会导致不确定的行为 。
Instead, simply query for a pointer into the resource section, together with the string length, and construct a new std::wstring
object on this data: 相反,只需查询指向资源部分的指针以及字符串长度,然后在此数据上构造一个新的
std::wstring
对象:
std::wstring LoadStringW( unsigned int id )
{
const wchar_t* p = nullptr;
int len = ::LoadStringW( nullptr, id, reinterpret_cast<LPWSTR>( &p ), 0 );
if ( len > 0 )
{
return std::wstring( p, static_cast<size_t>( len ) );
}
// Return empty string; optionally replace with throwing an exception.
return std::wstring();
}
There are a few points worth noting: 有几点值得注意:
0
for nBufferMax . 0
。 Doing so returns a pointer into the resource section; nBufferMax :
nBufferMax :
If this parameter is 0, then lpBuffer receives a read-only pointer to the resource itself.如果此参数为0,则lpBuffer接收指向资源本身的只读指针。
NUL
characters. NUL
字符。 This mandates the use of a std::string constructor taking an explicit length argument. return std::wstring(p);
would potentially truncate the returned string.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.