0

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?

ROBERT RICHARDSON
  • 2,077
  • 4
  • 24
  • 57
  • `AllocSysString()` creates a *copy*, so `bstrName` will be fine independent of `baseString`. Though, why would you want to do that? `CComBSTR` has a [c'tor](https://learn.microsoft.com/en-us/cpp/atl/reference/ccombstr-class#ccombstr) that takes a `LPCSTR`/`LPCOLESTR`, which `CString` has conversion operators for. Meaning that you can simply write `UseMyStringAsBSTR(CComBSTR(myString));` and all memory management is handled. – IInspectable May 25 '23 at 04:11

0 Answers0