为什么我不能分配 const 值,我应该怎么做?
我有一段带有以下粗略签名的代码:
void evaluate(object * this)
{
static const int briefList[] = { CONSTANT_A, CONSTANT_Z };
static const int fullList[] = { CONSTANT_A, CONSTANT_B, ..., CONSTANT_Z};
const int const * pArray;
const int nElements;
int i;
if ( this->needDeepsEvaluation )
{
pArray = fullList;
nElements = sizeof(fullList) / sizeof(fullList[0]);
}
else
{
pArray = briefList;
nElements = sizeof(briefList) / sizeof(briefList[0]);
}
for ( i = nElements; i; i-- )
{
/* A thousand lines of optimized code */
}
this->needsDeepEvaluation = 0;
}
大多数编译器会很乐意接受 pArray 的赋值,但会因 nElements 的赋值而窒息。 这种矛盾让我很困惑,希望得到启发。
我毫不犹豫地接受你不能分配一个 const 整数,但是为什么它会像我期望的 const 指针到 const 一样工作呢?
快速且廉价的修复方法是删除 const 限定符,但这可能会引入微妙的错误,因为循环内的大部分代码都是宏化的(我曾经被这个问题困扰过一次)。 您将如何重组上述内容以允许恒定元素计数器?
I have a piece of code with the following rough signature:
void evaluate(object * this)
{
static const int briefList[] = { CONSTANT_A, CONSTANT_Z };
static const int fullList[] = { CONSTANT_A, CONSTANT_B, ..., CONSTANT_Z};
const int const * pArray;
const int nElements;
int i;
if ( this->needDeepsEvaluation )
{
pArray = fullList;
nElements = sizeof(fullList) / sizeof(fullList[0]);
}
else
{
pArray = briefList;
nElements = sizeof(briefList) / sizeof(briefList[0]);
}
for ( i = nElements; i; i-- )
{
/* A thousand lines of optimized code */
}
this->needsDeepEvaluation = 0;
}
Most compilers will happily swallow the assignment of pArray, but chokes on the assignments of nElements. This inconsistency confuses me, and I would like to be enlightened.
I have no problem accepting that you can't assign a const integer, but then why does it works as I expect for the const-pointer-to-const?
The fast and cheap fix is to drop the const qualifier, but that might introduce subtle bugs since much of the code inside the loop is macrofied (I've been bitten by that once). How would you restructure the above to allow a constant element counter?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
正如米歇尔指出的那样,您的声明:
不太正确。
您有四 (4) 个语法选择:
As Michiel pointed out, your declaration:
isn't quite correct.
You have four (4) syntatic choices:
在
pArray
声明中,两个“const”关键字实际上都适用于
int
。 要使一个应用于指针,您必须将其声明为 int const * const pArray ,其中指针本身变得不可变。 然后,您的编译器应该对这两个赋值抛出错误。In your declaration of
pArray
Both 'const' keywords actually apply to
int
. To get one to apply to the pointer, you'd have to declare it asint const * const pArray
, in which the pointer itself becomes immutable. Your compiler should then throw an error on both assignments.我不知道 pArray 发生了什么,但是对于 nElements,您可以使用三元而不是 if-else:
如果您不喜欢三元,请声明一个计算 nElements 的小函数,并使用它来初始化。
I have no idea what's up with pArray, but for nElements you can just use a ternary instead of if-else:
If you don't like ternaries, declare a little function that computes nElements, and use that to initialize.