Content deleted Content added
No edit summary |
TranquilHope (talk | contribs) m Reverted 1 edit by 103.48.140.152 identified as test/vandalism using STiki |
||
Line 8:
=== Wrapping resources in objects ===
Wrapping resources in objects is the object-oriented form of [[Encapsulation (computer programming)|encapsulation]], and underlies the dispose pattern.
Resources are typically represented by [[Handle (computing)|handles]] (abstract references), concretely usually integers, which are used to communicate with an external system that provides the resource. For example, files are provided by the [[operating system]] (specifically the [[file system]]), which in many systems represents files with a [[file descriptor]] (an integer representing the file).
For example, in [[C file input/output]], files are represented by
<source lang="c">
Line 39 ⟶ 40:
An alternative to requiring explicit disposal is to tie resource management to [[object lifetime]]: resources are acquired during [[object creation]], and released during [[object destruction]]. This approach is known as the [[Resource Acquisition Is Initialization]] (RAII) idiom, and is used in languages with deterministic memory management (e.g. [[C++]]). In this case, in the example above, the resource is acquired when the file object is created, and when the scope of the variable <code>f</code> is exited, the file object that <code>f</code> refers to is destroyed, and as part of this, the resource is released.
RAII relies on object lifetime being deterministic; however, with automatic memory management, [[object lifetime]] is not a concern of the programmer: objects are destroyed at some point after they are no longer used, but ''when'' is abstracted. Indeed, lifetime is often not deterministic, though it may be, notably if
Thus by not coupling resource management to object lifetime, the dispose pattern allows ''resources'' to be released promptly, while giving implementation flexibility for memory management. The cost of this is that resources must be managed manually, which can be tedious and error-prone.
|