Resource acquisition is initialization: Difference between revisions

Content deleted Content added
m linking
Line 167:
| accessdate=2019-03-09}}</ref> manage object lifetime by [[reference counting]], which makes it possible to use RAII. Objects that are no longer referenced are immediately destroyed or finalized and released, so a [[Destructor (computer programming)|destructor]] or [[finalizer]] can release the resource at that time. However, it is not always idiomatic in such languages, and is specifically discouraged in Python (in favor of [[context manager]]s and ''finalizers'' from the ''weakref'' package).
 
However, object lifetimes are not necessarily bound to any scope, and objects may be destroyed non-deterministically or not at all. This makes it possible to accidentally leak resources that should have been released at the end of some scope. Objects stored in a [[static variable]] (notably a [[global variable]]) may not be finalized when the program terminates, so their resources are not released; CPython makes no guarantee of finalizing such objects, for instance. Further, objects with circular references will not be collected by a simple reference counter, and will live indeterminately long; even if collected (by more sophisticated garbage collection), destruction time and destruction order will be non-deterministic. In CPython there is a cycle detector which detects cycles and finalizes the objects in the cycle, though prior to CPython 3.4, cycles are not collected if any object in the cycle has a finalizer.<ref>{{cite web
| url=https://docs.python.org/3/library/gc.html
| title=gc — Garbage Collector interface