开发者

What is 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?


Pick an error HRESULT value and use that, so HRESULT hr = E_UNEXPECTED or HRESULT hr = E_FAIL would be good choices I expect.


I would use:

HRESULT hr = NOERROR;

You could also use

HRESULT hr = S_OK;

Both set it to 0.


Depends on chat you want:

  • Fail by default ? Use E_FAIL
  • Success by default ? use 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:

  • Declare variables as close to first use as practically possible.
  • Translate error codes and HRESULTs to C++ exceptions.
  • Wrap API functions that you use repeatedly and that have particularly ungood design.

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 HRESULTs 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); }
};
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜