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

StackOverflow https://stackoverflow.com/questions/20133199

  •  03-08-2022
  •  | 
  •  

문제

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? i.e. should I have:

 char *tmp = W2A(textValue);
 a.name = tmp;
 // do something to deallocate tmp?
도움이 되었습니까?

해결책

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.

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top