为什么使用循环变量时地址会发生变化? [英] Why is the address of a loop variable changing when using it?
本文介绍了为什么使用循环变量时地址会发生变化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
程序1:
library(pryr)
for (x in 1:3) {
print(c(address(x), refs(x)))
}
输出例如:
[1] "0x7a6a6c8" "1"
[1] "0x7a6a6c8" "1"
[1] "0x7a6a6c8" "1"
程序2:
library(pryr)
for (x in 1:3) {
print(c(address(x), refs(x)))
print(x)
}
输出例如:
[1] "0x7ae0298" "1"
[1] 1
[1] "0x7ae88c8" "1"
[1] 2
[1] "0x7af2668" "1"
[1] 3
显然,在程序2中x的值正在更改,但是为什么地址也更改?当for循环运行约500,000,000次而在循环期间未调用gc时,这是否会导致内存泄漏?
Obviously the value of x is changing in Program 2, but why is the adress changing too? Can this lead to memory leaks when having a for loop running about 500,000,000 times while the gc is not called during the loop?
推荐答案
在循环末尾具有print(x)会将其标记为多引用,如@alexis_laz所述.由于R是一种动态语言,因此这很容易发生.为了测试其效果,我们可以打印refs(x),print(x),refs(x)的输出:
Having print(x) at the end of the loop marks it as multi-reference, as @alexis_laz mentioned. Since R is a dynamic language, this can happen easily. To test the effects of this, we can print the output of refs(x), print(x), refs(x):
for (x in 1:3) {
print(refs(x))
print(x)
print(refs(x)); cat("\n")
}
输出:
[1] 1
[1] 1
[1] 2
[1] 1
[1] 2
[1] 2
[1] 1
[1] 3
[1] 2
这篇关于为什么使用循环变量时地址会发生变化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文