Should functions clean up after themselves?

  • Thread starter Thread starter Doug Haber
  • Start date Start date
D

Doug Haber

Hi All,

I know this probably sounds pretty obvious, but lets say I have a function
like:
HRESULT getDevice(IWMDMDevice3* pIDevice)

If it returns E_FAIL, then the pointer may be in an invalid state (but
non-NULL). Is it common practice for the function to clean up the pointer
or is it the responsibility of the caller (since the result failed)? Also,
what does clean up mean (since it's a COM object) Call Release()? Set it to
NULL? Both?

Thanks!

-D
 
Hi All,

I know this probably sounds pretty obvious, but lets say I have a function
like:
HRESULT getDevice(IWMDMDevice3* pIDevice)

If it returns E_FAIL, then the pointer may be in an invalid state (but
non-NULL). Is it common practice for the function to clean up the pointer
or is it the responsibility of the caller (since the result failed)? Also,
what does clean up mean (since it's a COM object) Call Release()? Set it to
NULL? Both?

This only makes sense to me provided pIDevice is an IWMDMDevice3**, and
getDevice sets *pIDevice. If this is the case, then you should not return a
valid COM pointer in *pIDevice if the function fails. You should set
*pIDevice to NULL and do whatever is necessary to free *pIDevice; if you
created the object, you would need to call Release, but if you obtained it
by other means, you may or may not need to call Release. To determine if
Release is required, consult the documentation relevant to how you obtained
the interface pointer.
 
Thanks Doug! Can you explain why I would need IWMDMDevice3**?

You need a pointer-to-pointer (or reference to a pointer) in order for
getDevice to change the parameter such that the caller would observe the
change. If that isn't what your function does, can you show briefly what it
does do? (A line or two of pseudocode and comments should be plenty.)
 
Back
Top