【发布时间】:2022-01-20 04:52:42
【问题描述】:
Python 使用引用计数。这意味着,如果不再引用某个值,则该值的内存将被回收。或者换句话说。只要至少还有一个剩余引用,就不会删除obj,也不会释放内存。
让我们考虑以下示例:
def myfn():
result = work_with(BigObj()) # reference 1 to BigObj is on the stack frame.
# Not yet counting any
# reference inside of work_with function
# after work_with returns: The stack frame
# and reference 1 are deleted. memory of BigObj
# is released
return result
def work_with(big_obj): # here we have another reference to BigObj
big_obj = None # let's assume, that need more memory and we don't
# need big_obj any_more
# the reference inside work_with is deleted. However,
# there is still the reference on the stack. So the
# memory is not released until work_with returns
other_big_obj = BigObj() # we need the memory for another BigObj -> we may run
# out of memory here
所以我的问题是:
为什么 CPython 对传递给堆栈上的函数的值持有额外的引用?这背后有什么特殊目的,还是只是一个“不幸”的实现细节?
我对此的第一个想法是: 防止引用计数降至零。但是,我们在被调用函数中仍然有一个活动引用。所以这对我来说没有任何意义。
【问题讨论】:
-
我认为这背后没有任何理由。这正是 CPython 在函数调用中实现临时引用的方式。出于同样的原因,
sys.getrefcount()给原始引用 +1,因为堆栈帧中的临时引用。 -
非常有趣。行为从 3.5(无附加参考)更改为 3.6(有附加参考)。
标签: python function cpython reference-counting