Ö
Öö Tiib
It fits when there is a useful concept of lifetime, but, to take one
example, Smalltalk has garbage collection, and there is no concept of
the lifetime of an object that is of any use to the programmer.
That is _the_ problem that destructors solve. Objects have birth and death.
Name one real life object that does not have it? If destructors are missing
then developer can still manually turn object into some custom-made "dead"
state ready for disposal by garbage collector. That is inconvenient if user
does not want to deal with aspect of killing object ("what means i have to
close the configuration?") and also the encapsulation now leaks
information ("you must close the configuration because there is underlying
file open").
In another post (it's a shame I can't reply to both at once) you mention
the huge benefit of destructors in resource management (open file,
dynamically allocated memory and so on).
Benefit is not automatic management of precious resources. OOP does not
need it. OOP involves restricting unneeded access to underlying precious
resources of abstraction and bundling those with needed (for user) operations
that involve the resources. That is called "encapsulation". It can not be done
perfectly if outside user of abstraction _must_ deal with lifetime (to kill,
close, free, join) underlying precious resources of abstraction. Such
manipulations _can_ still be among operations with abstraction but usage
of those _is not_ among mandatory responsibilities of user of abstraction
anymore thanks to destructors.
Where the language has the
right concepts, this is true, but it does not imply an object-oriented
language. One can image C+exceptions in which a variable can be tagged
with code to be executed at the end of its lifetime:
FILE *fp = NULL on byebye = { if (fp) fclose(fp); }
I did nowhere say that destructors (or RAII) can be /only/ used for OOP. Use how
you want. I said that destructor and RAII idiom are very beneficial featurefor
OOP features like information hiding, encapsulation and separation of concerns.
We'd have destructors, but not OO. In other words, the two concepts are
orthogonal. Destructors may not even make sense in an object-oriented
language, and they may be present in one that is not OO.
Yes. Similarly a pine may be in garden, in park or in forest. Pine is not forest,
pine is tree and there may be forest without pine. However there can't be forest
without trees and pine is good, straight tree in forest.
Obviously C++ relates the two by being object-oriented (in part) and by
having destructors, but that does not mean there is any logical
connection between the two concepts.
It is like to claim that there are no logical connections between pine and
forest? World largest forests (see "taiga") are mostly pines, spruces and larches.
So world forests would be _lot_ poorer without those pines.