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)
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With