我正在使用Visual Studio 2005中的C++,出现了许多警告,内容如下:
potentially uninitialized local variable 'hr' used
hr被定义为
HRESULT hr;
如何正确地初始化 HRESULT?
我正在使用Visual Studio 2005中的C++,出现了许多警告,内容如下:
potentially uninitialized local variable 'hr' used
hr被定义为
HRESULT hr;
如何正确地初始化 HRESULT?
选择一个错误的 HRESULT
值并使用它,所以 HRESULT hr = E_UNEXPECTED
或 HRESULT hr = E_FAIL
将是不错的选择。
HRESULT hr = NOERROR;
HRESULT hr = S_OK;
两者都将其设置为0。
根据你想要的聊天效果而定:
E_FAIL
S_OK
hr
值不相关?使用 E_UNEXPECTED
不要通过初始化变量来抑制警告。这些警告告诉你代码有问题。修复代码。
一些有用的技巧:
HRESULT
转换为 C++ 异常。将 HRESULT
转换为异常可以通过使用 ">>
throwing pattern" 非常简洁地完成,几乎可读性强,例如(虽然此示例不涉及 HRESULT
,但它显示该模式概括了大多数 C 风格方案)...
std::ostream& operator<<( std::ostream& stream, wchar_t const s[] )
{
Size const nBytes = wcstombs( 0, s, 0 );
(nBytes >= 0)
|| throwX( "wcstombs failed to deduce buffer size" );
Size const bufSize = nBytes + 1;
std::vector< char > buf( bufSize );
// The count of bytes written does not include terminating nullbyte.
wcstombs( &buf[0], s, bufSize )
>> Accept< IsNonNegative >()
|| throwX( "wcstombs failed to convert string" );
return (stream << &buf[0]);
}
所需的支持定义并不复杂,例如:
inline bool throwX( std::string const& s )
{
throw Failure( s );
}
template< class Predicate >
struct Accept: Predicate
{};
template< class Type, class Predicate >
inline bool operator>>( Type const& v, Accept< Predicate > const& isOK )
{
return isOK( v );
}
struct IsNonNegative
{
template< class Type >
bool operator()( Type const& v ) const { return (v >= 0); }
};
>>
重载?这真的是世界需要的吗?;) - jalf>>
重载(除了iostreams中的)。 - Cheers and hth. - Alf