这是一种设计上的怀疑。场景:我有一个包含一些整数元素的数组。在我的代码库中,这个数组由1个模块(.so)填充,比如X。然后它被共享给另一个模块Y (.so)。在运行时,X模块识别出模块Y需要处理数组的几个字段并对其进行修改,这就是X将数组共享给Y的原因。(这两个so都被消耗到一个二进制文件中。)一旦Y返回,模块X将打印数组。
问题:我如何通过编程强制模块Y不修改除由X标识的数组索引之外的任何其他数组索引。整个数组都是在模块之间传递的,我不能把它设为常量,因为这样Y就不能改变任何字段了。SInce。您可以说,我想对运行时标识的几个字段强制执行常量。
发布于 2014-08-22 09:30:55
这样如何:
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
}https://stackoverflow.com/questions/25422425
复制相似问题