6.5(p7)
指出:
An object shall have its stored value accessed only by an lvalue expression that has one of the following types:88)
— a type compatible the effective type of the object,
— a qualified version of a type compatible with the effective type of the object,
— a type that is the signed or unsigned type corresponding to the effective type of the object,
— a type that is the signed or unsigned type corresponding to a qualified version of the effective type of the object,
看看 6.7.3(p10)
:
For two qualified types to be compatible, both shall have the identically qualified version of a compatible type;
所以 double
和 const double
不兼容,因为它们的类型限定符不一样。
现在我假设signed or unsigned type 是指 signed or unsigned integer type as defined it 6.2.5(p4)
和 6.2.5(p6)
相应地,因为 6.2.5
本身没有定义签名类型。
现在考虑以下代码:
void print_double(const double d){
printf("d = %lf\n", d);
}
int main(int args, const char *argv[]){
double d = 10.2;
print_double(d);
}
现在我尝试应用 6.5 (p7)
:
我。 与对象的有效类型兼容的类型
不,const double
和 double
不兼容。
二。 与对象的有效类型兼容的类型的合格版本
不,const double
的合格版本会比 const double
更合格
三/四。
不,double
不是有符号或无符号整数类型。
这个判断似乎是错误的,因为通过 const 限定的左值访问非常量对象应该是可以的。但我无法从 6.5(p7)
中得出它。
最佳答案
Now consider the following code:
void print_double(const double d){ printf("d = %lf\n", d); } int main(int args, const char *argv[]){ double d = 10.2; print_double(d); }
您的代码不做任何别名。 main 中的 d
和 print_double
中的 d
是 distinct 对象,因为参数总是按值传递。但是如果我们要“修复”这个例子:
void print_double(const double *pd){
printf("d = %lf\n", *pd);
}
int main(int args, const char *argv[]){
double d = 10.2;
print_double(&d);
}
它仍然定义明确。 *pd
是 const double
类型的左值。 const double
是 double
的合格版本。所有类型都与自身兼容(平凡)。所以第二个项目符号成立,这个别名是有效的。
关于c - 通过 const 左值访问非常量对象是否安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55236473/