Reputation: 4385
std::map<int, _variant_t> myMap;
PWCHAR myData= NULL;
//Set myData to some value.
myMap.insert(std::pair<enStoreArchive, _variant_t>(1, myData ));
In the above code sample, I have a map which contains a variant pointing to a PWCHAR (bstr).
http://roblocher.com/whitepapers/oletypes.html says that variants will free a BSTR assigned to it, but another line says that values in pointer assigned to _variant_t needs to be manually freed.
Do I need to manally free myData or will _variant_t take care of it?
Upvotes: 2
Views: 715
Reputation: 942119
VARIANT is an interop type, designed to be useable from different languages that have different runtime implementations. There is nothing interopable about a WCHAR*, destroying the string buffer cannot be done reliably without the consumer knowing what heap it was allocated on. Or for that matter if it is even stored on a heap or came from the same process.
So Windows provides a string type that has guaranteed allocate and release semantics, it is BSTR
. Underlying winapi calls are SysAllocString() and SysFreeString(). Storage is allocated from a dedicated heap, the one that CoTaskMemAlloc() allocates from. Also used by SAFEARRAY, another variable length type that requires the same guarantees.
So only way it can work is that your string is copied. Done by the _variant_t constructor that takes a const wchar_t*, it calls SysAllocString(). It is therefore up to you to destroy your string buffer again, you can do so immediately after you assigned it to the variant. The _variant_t destructor takes care of automatically destroying the copy.
Upvotes: 2
Reputation: 6050
If you look at the destructor of _variant_t, you will see that it calls the windows API VariantClear().
However, the constructor of _variant_t will allocate new data for it. Therefore, if you use it wrong, you may need to delete myData. Your current example just shows a NULL pointer. It's not very helpful at all.
The _variant_t will allocate its own data and really has nothing to do with the memory allocated for myData. If you allocate memory for myData, you will have to deallocate it--because the _variant_t is going to make its own copy.
Upvotes: 2