c++在模块间共享数组元素,仅对少数字段具有const性

C++ sharing array elements across modules with const-ness for few fields only

本文关键字:数字段 const 模块 共享 数组元素 c++      更新时间:2023-10-16

这是一种设计疑问。场景:我有一个包含一些整数元素的数组。该数组由代码库x中的1个模块(.so)填充,然后共享给另一个模块Y (.so)。在运行时,X模块确定模块Y需要处理数组的几个字段并对其进行修改,这就是X将数组共享给Y的原因。(这两个都被消耗成一个二进制。)一旦Y返回模块,X打印数组。

问题:我如何通过编程强制模块Y不修改除X标识的索引以外的任何其他数组索引?由于整个数组在模块之间传递,我不能使其为const,因为Y将无法更改任何字段。你可以说,我想在运行时对几个字段执行const-ness。

这个怎么样:

template <class T> class CProtectedArray {
private:
    T*              m_aItems;
    unsigned int*   m_aMask;
public:
    CProtectedArray(int cElem, bool fInitialProtect) : m_aItems(NULL)  {
        int cbElem = sizeof(T)*cElem;
        int cbMask = sizeof(int)*(cElem+31)/32;
        m_aItems = (T*)malloc(cbElem + cbMask);
        m_aMask = (unsigned int*)(m_aItems + cElem);
        memset(m_aItems, 0, cbElem);
        memset(m_aMask, fInitialProtect ? -1 : 0, cbMask);
    }
    ~CProtectedArray() {
        if (m_aItems)
            free(m_aItems);
    }
    bool IsProtected(int iItem)     { return !!(m_aMask[iItem>>5] & (1<<(iItem&31))); }
    void Protect(int iItem)         { m_aMask[iItem>>5] |= 1<<(iItem&31); }
    void UnProtect(int iItem)       { m_aMask[iItem>>5] &= ~(1<<(iItem&31)); }
    void Set(int iItem, T val) {
        if (!IsProtected(iItem))
            m_aItems[iItem] = val;
    }
};
int main(int argc, char* argv[])
{
    CProtectedArray<int> A(100, true);
    bool f = A.IsProtected(30);  // f = true
    A.Set(30, 23);  // nothing happens
    A.UnProtect(30); 
    f = A.IsProtected(30);  // f = false
    A.Set(30, 24); // sets element 30 to 24
    A.Protect(30); 
    f = A.IsProtected(30);  // f = true
    A.Set(30, 25);  // nothing happens
}