anand_m used Ask the Experts™
I was reviewing a piece of code and came across this:

operator BSTR() {return ::SysAllocString(L"");}    

I guess this will cause a memory leak.

Is there a better way to do the same ?

Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
In COM standard this is an ordinary practice when server has to return output parameter as BSTR, for example

// server method
HRESULT getName(BSTR* name)
  *name = SysAllocString(L"something");

// client code

BSTR name = 0;

// do something with name here

//!!!!!! free resources
// client is responsible to free memory!!!

But you are right that the definition you describe above is a bad practice leading to the potential memory leak.

A better way is define a class member as _bstr_t
class A
      // internal using
      operator BSTR() { return _strName; }
      // make a copy for COM using
      BSTR copy() { return _strName.copy(); }

// ......
      _bstr_t _strName;
There are many BSTR smart pointer classes out there.  You may use the compiler COM support class: _bstr_t (comutil.h) or CComBSTR (atlbase.h).

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial