CComQIPtr is better than QueryInterface

Top  Previous  Next

Instead of doing a QueryInterface where you have to worry about Release etc., you can sometimes use a CComQIPtr, like this:

 

    CComQIPtr<DimensionConstraint> pDimConstraint ; // It is null now (cannot be initialised to NULL) 

    for (long iDim = 1 ; iDim <= ikNumRetDims ; iDim++) {

 

        TRACE (L"Looking at dim %d of %d\n",iDim,ikNumRetDims) ;

 

        // Look at the nth dimension in the collection...

        IDispatchPtr pNthDim;

        hRes = pAllRetCollection->get_Item(_variant_t(iDim), &pNthDim);

        if (FAILED (hRes)) {

            ShowCOMError (hRes,L"ShowNamedRetDimInView Could not get_Item %d",iDim) ;

            return ;

        } 

 

        pDimConstraint = pNthDim ; // This can be tested for NULL

 

        if (pDimConstraint != NULL) {            

            // We have a DimensionConstraint, what is the name of the model parameter?

 

 

CComPtr/CComQIPtr perform automatic reference counting for you (for example, they call Release on the interface attached to them, when the smart-pointer variable goes out of scope).

 

And CComQIPtr is null when you first create it. See comment on first line of the code above.

 

Text, images and diagrams © 2021 Owen F. Ransen. All rights reserved. (But copy the source code as much as you want!)