简体   繁体   中英

When using W2A to convert BSTR to std::string, is there any clean up needed?

Code looks like the following:

class A 
{
  public:
     std::string name;
};

A a;
CComBSTR textValue;
// some function which fills textValue
a.name = W2A(textValue);

Now, I've used CComBSTR so I don't have to dealloc the BString, but does W2A allocate any memory that I might have to deal with? ie should I have:

 char *tmp = W2A(textValue);
 a.name = tmp;
 // do something to deallocate tmp?

No cleanup is required because W2A allocates memory on the stack . There are certain memory-related pitfalls you have to be aware of (direct consequences of stack allocation), but nothing that looks immediately suspicious in this specific scenario.

Be very cautious with the W2A/A2W macros. They are implemented with "alloca" (dynamic allocation directly on the stack). In certain circumstances involving loop/recursion/long string, you will get a " stackoverflow " (no kidding).

The recommanded way is to use the "new" helpers templates. See ATL and MFC String Conversion Macros

A a;
CComBSTR textValue;
// some function which fills textValue
CW2A pszValue( textValue );
a.name = pszValue;

The conversion use a regular "in stack" buffer of 128 bytes. If it's to small, the heap is automatically used. You can adjust the trade-off by using directly the template types

A a;
CComBSTR textValue;
// some function which fills textValue
CW2AEX<32> pszValue( textValue );
a.name = pszValue;

Don't worry: you just reduced your stack usage, but if 32 bytes is not enough, the heap will be used. As I said, it's a trade-off. If you don't mind, use CW2A .

In either case, no clean up to do:-)

Beware, when pszValue goes out of scope, any pending char* to the conversion may be pointing to junk. Be sure to read the "Example 3 Incorrect use of conversion macros." and "A Warning Regarding Temporary Class Instances" in the above link.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM