[英]Why does the `const` modifier applied to a variable holding a struct value make the struct values immutable?
struct S { string s; }
void method()
{
const S s = { "s" };
s.s = "l"; // Error
}
I can't understand why a compile-error is being generated here.我不明白为什么这里会产生编译错误。 From my understanding, making a struct-referencing variable const
should make the variable itself immutable (only s = { "m" }
after s
initialization should generate error), not the structure itself (so ss = "l"
should pass OK).根据我的理解,制作一个结构引用变量const
应该使变量本身不可变(只有s = { "m" }
在s
初始化后应该产生错误),而不是结构本身(所以ss = "l"
应该通过 OK)。 Why const makes both the variable and the struct immutable?为什么 const 使变量和结构都不可变?
It's not "a variable referencing a struct instance".它不是“引用结构实例的变量”。 There's no indirection.没有间接性。 The value of s
is a struct S
, which includes all of its fields. s
的值是一个struct S
,它包括它的所有字段。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.