I'm using C++ in Visual Studio 2005 and I'm getting many warnings that read
potentially uninitialized local variable 'hr' used
Where hr is defined as
HRESULT hr;
What's the correct way to initialize HRESULT?
I'm using C++ in Visual Studio 2005 and I'm getting many warnings that read
potentially uninitialized local variable 'hr' used
Where hr is defined as
HRESULT hr;
What's the correct way to initialize HRESULT?
I would use:
HRESULT hr = NOERROR;
You could also use
HRESULT hr = S_OK;
Both set it to 0.
Pick an error HRESULT
value and use that, so HRESULT hr = E_UNEXPECTED
or HRESULT hr = E_FAIL
would be good choices I expect.
Depends on chat you want:
E_FAIL
S_OK
hr
value is irrelevant if the subsequent code fails to initialize it ? Use E_UNEXPECTED
Do not suppress the warnings by initializing the variables. The warnings are telling you that the code is Bad. Fix the code.
Some useful techniques:
HRESULT
s to C++ exceptions.Translating from HRESULT
to exception can be done very concisely and almost readably by using the ">>
throwing pattern", like (although this example doesn't involve HRESULT
s it shows that that pattern generalizes to handle most C style schemes) ...
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]);
}
The support definitions needed for this are not complex at all, e.g. like
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); }
};