c++在模块间共享数组元素,仅对少数字段具有const性
C++ sharing array elements across modules with const-ness for few fields only
这是一种设计疑问。场景:我有一个包含一些整数元素的数组。该数组由代码库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
}
相关文章:
- 如何使用函数的输出初始化 const 数组结构字段?
- 如何安全地将有符号字段从uint32_t提取到有符号数字(int或uint32_t)中
- 在这种情况下,如何从类型 "const char*" 初始化字段?
- 如何检查字段中输入的数字是否重复
- 如何使用 c++ 中的 int* count(const string&s)计算字符串中每个数字的出现次数?
- 这个(const vector<vector<int> > &A)"代码段是什么意思?
- 具有7个段显示的数字时钟,带有PIC18F445K22
- 使用静态方法初始化 const 类字段的做法是好是坏
- 为什么这段代码输出这么多数字
- 函数上的关键字'const'意味着对象字段完全只读?
- 当我将 const int 声明/初始化为 5 时,它被初始化为一个大数字
- Visual Studio 2015中的命令参数字段
- Const 引用字段作为类中的只读属性C++
- C 如何结束一个段循环,该循环添加数字而不使用数字作为触发器来结束循环
- 在构造函数中初始化const字段,但首先检查一个参数
- 初始化成员函数字段
- FP号码的指数字段不是我预期的,为什么?
- c++在模块间共享数组元素,仅对少数字段具有const性
- Setw()不影响读取整数字段
- 如何设置ostream的指数字段的宽度