类型之间的初始化“const int的**常量”和“INT **”是不允许的,为什么呢?

StackOverflow https://stackoverflow.com/questions/1468148

使用V1.8的z / OS XL C编译器,使用INFO(ALL)抬高式警告,我得到下面的代码的第4行以下警告:

WARNING CCN3196 Initialization between types "const int** const" and "int**" 
                is not allowed.


1  int foo = 0;
2  int *ptr = &foo;

3  const int * const fixed_readonly_ptr = ptr;

4  const int ** const fixed_ptr_to_readonly_ptr = &ptr;

我不能完成我的身边,为什么我得到这个警告头。如果我能一个int指针赋给一个const指向const int的(3号线),那么为什么我不能一个int指针的地址分配给一个const指针指向const int的?我缺少什么?

请注意上面的代码是一个精简下来例子只是表示我遇到的代码量小的问题。真正的背景是,我有一个const指针指向struct(的struct **常量)和我将它作为一个参数传递给函数谁的参数定义为一个const指针指向const的结构(常量的struct **常量)。这是因为该功能不会修改在结构(因此第一常数)的数据,并且它不修改它总是保持在传递的地址(因此第二常数)指针参数。该指针的值指向可通过的方式被改变(这就是为什么没有在之间的第三常量的**)。

有帮助吗?

解决方案

的C规则是可以的指针转换为某物的指针为const的东西,但的东西必须是完全相同的类型,包括常量和挥发性资格进一步向下链

该规则的理由是,如果这两条线的第二被允许:

int *ptr;

const int ** const fixed_ptr_to_readonly_ptr = &ptr;

然后这可以被用来打破类型安全性而不铸造。

const int i = 4;

// OK, both sides have type const int *
*fixed_ptr_to_readonly_ptr = &i;

// the value of fixed_ptr_to_readonly_ptr is still &ptr
// the value of ptr is now &i;

*ptr = 5;

// oops, attempt to change the value of i which is const

其他提示

这是一个安全型违反。考虑下面的代码(I改组const围绕一点,以明确是否适用于指针或指针对象,但语义它意味着同样的事情):

int* p = 0;
int const** pp = &p; // presumably ok

int const c = 123;
*pp = &c; // okay, &c is int const*, and *p is int const* lvalue

*p = 666; // okay, *p is int lvalue

// wait, so we just changed the value of (const) c above, with no const_cast!

这是一种类型的安全违规。你可能想用用const int * const的*代替。 请参见 http://www.parashift.com/c++ -faq-精简版/ const的-correctness.html#FAQ-18.17

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top