Boost logo

Boost Users :

From: Peter Dimov (pdimov_at_[hidden])
Date: 2007-01-04 13:32:17


Philipp Henkel wrote:

> CComPtr-like usage:
> boost::intrusive_ptr<IVideo> video;
> someObject->QueryInterface(IID_IVideo,(void**)&video);
>
> Is there a better way? How do you bring intrusive_ptr and
> QueryInterface together?

The technically correct way to use QueryInterface is to pass it the address
of a void*:

void* pv = 0;
someObject->QueryInterface( IID_IVideo, &pv );
IVideo * pv2 = static_cast< IVideo* >( pv );
boost::intrusive_ptr<IVideo> video( pv2 );
pv2->Release();

The (void**) cast is too error-prone, even if you don't care about
technicalities.

This of course can be encapsulated in a function.

template<class Target, class Source> intrusive_ptr<Target>
query_interface( Source ps, IID const & iid /* = __uuidof( Target ) */ )
{
    void* pv = 0;
    ps->QueryInterface( iid, &pv );
    Target * pv2 = static_cast< Target* >( pv );
    boost::intrusive_ptr<Target> target( pv2, false );
    return target;
}

and then

intrusive_ptr<IVideo> video = query_interface<IVideo>( someObject,
IID_IVideo );


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net