I find it hard to find clear examples that would explain how to read a COleSafeArray…
So I have an object that returns through a member function a _variant_t that is actually a COleSafeArray . I want to read it’s element and make sure I’m not leaking memory…
Here is a kind of sample code. I am just trying to read the ifrst element of the array which I assume to be a long. There’s more data in the array.
class ExampleObject
{
_variant_t GetArray();
};
//...
long Read(ExmapleObject* ptr)
{
COleSafeArray the_array = ptr->GetArray();
VARIANT value_temp;
VariantInit(&value_temp);
long index = 0;
the_array.GetElement(&index, &value_temp);
long my_result = value_temp.lVal;
return my_result;
}
Is there anything wrong in this code that may generate memory leaks ?
Efficient read of
COleSafeArraycontents is about reliability and performance.To read reliably, avoid junk and leaking, you should check types of the array itself and the elements. The
.vtfield tells you the type of array, which might be array of specific [fixed] type, or array ofVARIANT, which in turn might embed sub-arrays.You have options to get individual elements using
GetElement, in which case if the data element is a string, object, or variant, the function copies the element in the correct way, and hence you are responsible for clearing the copy. To have it done for you by a wrapper class, get your elements intoCComVariantclass variable, as opposed toVARIANTstruct (~CComVariantwill clean things up for you).Or, otherwise having type checked you can Lock/Unlock array and obtain direct access to elements managed by the array. You might prefer this method for performance because you lock once and copy if needed, as opposed to having locks and copies per element in previous access option.
~COleSafeArraydestructor clears the elements of the array, so you don’t have to destroy/release them explicitly.