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

  • 这在实践中是否安全,记住代码只能在 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();
    

    最佳答案

    是的,CComVariant 旨在直接替代 VARIANT。它源自变体结构,不添加虚拟成员或字段(也没有虚拟析构函数)以确保内存布局相同。许多像 ATL/MFC 中的小助手类,如 CRect、CPoint 等。

    关于c++ - 当大小相同时,使用派生对象数组作为基础对象数组 (CComVariant/VARIANT),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2957062/

    10-11 22:54
    查看更多