Raw pointers in function signatures
Rather than having a smart pointer in the function signature, consider using a raw pointer to save the overhead of a call to the smart pointer constructor upon invocation of the function. You can still pass smart pointer objects to functions since each smart pointer has an overloaded pointer operator that returns the underlying raw pointer. The following example illustrates this:
[C++]
HRESULT DoRasterOp(IRaster *pRaster); // Function dec: raw pointer
IRasterPtr ipRaster;
HRESULT hr = DoRasterOp(ipRaster); // Pass in smart pointer
For the sake of simplicity, the code snippets given don't always check HRESULT's, although as a developer you should always do so.
Return ArcObjects from functions
This tip builds on the previous one. In this case, raw pointers are used in the function declaration and a double indirection is used for the object that will be returned. This allows you to alter what the pointer you are passed points to. Next, initialize a smart pointer object with the value you wish to return and assign it to the pointer you were passed in. Notice the call to AddRef(). This is required to ensure that resources are managed properly.
[C++]
HRESULT GetTinWorkspace(char *path, ITinWorkspace **ppTinWorkspace)
{
if (!ppTinWorkspace)
return E_POINTER;
HRESULT hr = S_OK;
IWorkspaceFactoryPtr ipWorkspaceFactory(CLSID_TinWorkspaceFactory);
IWorkspacePtr ipWork;
hr = ipWorkspaceFactory->OpenFromFile(CComBSTR(path), 0, &ipWork);
if (FAILED(hr) || ipWork == 0)
return E_FAIL;
// Initialize ipTinWorkspace with ipWork
ITinWorkspacePtr ipTinWorkspace(ipWork);
*ppTinWorkspace = ipTinWorkspace;
// AddRef() if the assignment workedif (*ppTinWorkspace)
(*ppTinWorkspace)->AddRef();
return hr;
}