开发者

Using an array of derived objects as an array of base objects when the sizes are the same (CComVariant/VARIANT)

I'm using code that treats an array of derived objects as an array of base objects. The size of both objects is the same. I'm wondering:

  • Is this safe in practice, bearing in mind that the code will only ever be compiled on Microsoft compilers?

Here's my example:

BOOST_STATIC_ASSERT(sizeof(VARIANT)==sizeof(CComVariant));

//auto_array deletes[] the pointer if detach() isn't called at the end of scope
auto_a开发者_开发知识库rray<CComVariant> buffer(new CComVariant[bufferSize]);

//...Code that sets the value of each element...

//This takes a range specified as two VARIANT* - the AtlFlagTakeOwnership option
//causes delete[] to be called on the array when the object pEnum referes to 
//is released.
pEnum->Init(buffer.ptr,buffer.ptr+bufferSize,0,AtlFlagTakeOwnership);
buffer.detach();


Yes, CComVariant was designed to be a direct substitute for VARIANT. It derives from the variant structure and adds no virtual members nor fields (and no virtual destructor) to ensure the memory layout is the same. Lots of little helper classes like that in ATL/MFC, like CRect, CPoint etc.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜