章节【失效的可变性】示例请教 #350
shenshouer
started this conversation in
内容建议
Replies: 1 comment
-
@sunface 大佬,不知道我的理解是否正确,求教 |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
失效的可变性 中最后的例子给出的提示是不是有错误?

提示内容如下图
如果修改成下面的代码:
只保留
a.f1 = 10;
是不是一样会给出报错?原因是:定义了一个可变变量a, 并将a赋值给了b变量的字段,这个时候存在了2个可变引用,如果不再引用使用a变量的话, 根据NLL规则,a的生命周期因该在赋值给变量b后就失效了。而修改后的代码将继续使用a变量造成a的生命周期一直持续到当前为止(甚至到main结束), 此时变量a与变量b有重叠生命周期,这重叠生命周期中存在两个a的可变引用,因此应该报错
Beta Was this translation helpful? Give feedback.
All reactions