当大小相同时,使用派生对象数组作为基础对象数组(CComVariant / VARIANT)

时间:2010-06-02 11:08:38

标签: c++ arrays com atl

我正在使用将派生对象数组视为基础对象数组的代码。两个对象的大小是相同的。我想知道:

  • 这在实践中是否安全,请记住代码只会在Microsoft编译器上编译?

这是我的例子:

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 个答案:

答案 0 :(得分:1)

是的,CComVariant旨在成为VARIANT的直接替代品。它派生自变体结构,并且不添加虚拟成员或字段(并且不添加虚拟析构函数)以确保内存布局相同。很多像ATLC / MFC那样的小助手类,比如CRect,CPoint等。