tags:

views:

50

answers:

1

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_array<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();
+1  A: 

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.

Hans Passant