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

I use code that treats an array of derived objects as an array of basic objects. The size of both objects is the same. I am wondering:

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

Here is 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(); 
+4
source share
1 answer

Yes, CComVariant was intended to be a direct replacement for VARIANT. It is based on the structure of options and does not add any virtual members and fields (and no virtual destructor) to ensure that the memory layout is the same. Many small helper classes like ATL / MFC such as CRect, CPoint, etc.

+1
source

Source: https://habr.com/ru/post/1311605/


All Articles