开发者

How to Store a VARIANT

I need to store a VARIANT of type bstr in a stl vector. I'm not sure how should I store VARIANT type in vector.

vector<VARIANT> vec_MyVec;

    VARIANT var开发者_高级运维_Temp;
    VariantInit(&var_Temp);
    var_Temp.vt = VT_BSTR
    var_Temp.bstrVal = SysAllocString("Test");

vec_MyVec.push_back(var_Temp);

Is this implementation cause a memory leak ? What would be the best way to store VARIANTS ?

Thank you


Yes, you're leaking memory.

Whenever you allocate memory with the SysAllocString family, you must either free it using SysFreeString or pass it to something that will take responsibility for freeing it. The VARIANT type does not clean up its own memory.

You have a couple of options for fixing it:

  • Use CComVariant or variant_t. It provides an operator=, copy constructors and a destructor that manage the memory for you. The drawback to storing them in a vector is that temporary copies will be created and destroyed (the same as if you'd stored std::string). This is the easiest, and my preferred, solution.

  • Call SysFreeString on every string in vec_MyVec when you're finished. This is more efficient but also much more error prone and difficult to do correctly, especially when considering exception safety.

  • Store a vector of std::tr1::shared_ptr<CComVariant>, this will prevent temporary copies being created, but you'll have the overhead of reference counting instead.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜