Search code examples
visual-c++com

Do we need to free the memory of a WCHAR[] assigned to a _variant_t?


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?


Solution

  • 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.