People in my team (or formerly in my team) did not pay enough attention to memory management of strings in COM. There are far too many example of this:
CString myString = _T("My String");
UseMyStringAsBSTR(myString.AllocSysString());
There is no corresponding call to SysFreeString().
One web page I found suggests a construct like this:
CString myString = _T("My String");
CComBSTR myBstr;
myBstr.Attach(myString);
UseMyStringAsBstr(myBstr);
That will free the allocated memory automatically when myBstr goes out of scope.
It seems to me that this could be simplified by a macro. The following seems to work:
#define MAKE_COMBSTR(bstrName, contents) \
CComBSTR bstrName; \
{ \
CString baseString = (contents); \
bstrName.Attach(baseString.AllocSysString()); \
}
This seems to work, but I'm a little nervous about declaring baseString, calling Attach(), and then having baseString go out of scope. Is there any danger of bstrName trying to baseString's memory after it doesn't exist any more?