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.