2010-06-02 62 views
4

我使用的代碼將派生對象的數組視爲基礎對象的數組。兩個對象的大小是相同的。我想知道:當尺寸相同時使用派生對象的數組作爲基礎對象的數組(CComVariant/VARIANT)

  • 這是否在實踐中是安全的,牢記代碼只能在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

是的,CComVariant被設計爲VARIANT的直接替代品。它來源於變體結構,並且不添加虛擬成員或字段(也沒有虛擬析構函數)以確保內存佈局相同。許多類似ATL/MFC的輔助類,如CRect,CPoint等。

相關問題