Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a CComPtr to a function with a raw pointer prototype

I'm going through some legacy C++ code dealing with the Windows Imaging Component library and I observed this:

void setProperties(IPropertyBag2* const pBag)
{  
   pBag->Write(...);
}

void other_function()
{
   CComPtr<IPropertyBag2> pBag;
   //Code to initialize pBag
   setProperties(pBag);
}

The setProperties method simply writes a bunch of properties to the property bag. The code compiles and runs fine because I think it calls the appropriate typecasting operator.

My question is whether such an interface is recommended or is there a better way of passing the pointer. For example, is there any difference (in terms of safety/ performance) if the signature was changed to:

void setProperties(const CComPtr<IPropertyBag2>& pBag)
like image 330
Sau Avatar asked Sep 21 '12 02:09

Sau


2 Answers

Raw interface pointers are the canonical way to work with COM objects. They are also the most flexible. Using a reference to a CComPtr will tie you into using CComPtr always.

Any COM pointer, even a dumb one, is automatically a smart pointer since the object itself implements AddRef and Release. If the function isn't keeping a copy of the pointer there's no need even to worry about that.

The CComPtr type will automatically cast itself to a raw pointer for convenience.

like image 167
Mark Ransom Avatar answered Oct 23 '22 04:10

Mark Ransom


There aren't many advantages to using a CComPtr parameter (unless it's non-const and you're going to modify it). CComPtr is more useful for local variables and instance variables.

But it's OK to do it, if only as a matter of style/consistency.

like image 39
user1610015 Avatar answered Oct 23 '22 04:10

user1610015