在阅读 python C/API 的文档时,有一些术语涉及引用窃取和借用。它们是什么意思?
最佳答案
正如 user2864740 评论的那样,这些术语在 Reference Count Details section 中定义。 Python C API 文档的“介绍”页面。以下是相关段落:
The reference count behavior of functions in the Python/C API is best explained in terms of ownership of references. Ownership pertains to references, never to objects (objects are not owned: they are always shared). “Owning a reference” means being responsible for calling Py_DECREF on it when the reference is no longer needed. Ownership can also be transferred, meaning that the code that receives ownership of the reference then becomes responsible for eventually decref’ing it by calling Py_DECREF() or Py_XDECREF() when it’s no longer needed—or passing on this responsibility (usually to its caller). When a function passes ownership of a reference on to its caller, the caller is said to receive a new reference. When no ownership is transferred, the caller is said to borrow the reference. Nothing needs to be done for a borrowed reference.
Conversely, when a calling function passes in a reference to an object, there are two possibilities: the function steals a reference to the object, or it does not. Stealing a reference means that when you pass a reference to a function, that function assumes that it now owns that reference, and you are not responsible for it any longer.
关于python - 什么是引用窃取和借用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23644926/