Re: Article on possible improvements to C++
On Nov 30, 8:18 pm, Joshua Maurice <joshuamaur...@gmail.com> wrote:
On Nov 30, 9:41 am, James Kanze <james.ka...@gmail.com> wrote:
On Nov 30, 10:11 am, Nick Keighley <nick_keighley_nos...@hotmail.com>
On 27 Nov, 10:59, "Balog Pal" <p...@lib.hu> wrote:
The style is like:
- 'delete' is forbidden in "client" code. It is privilige
of the the few library classes that serve as managers.
and who holds the auto-ptr?
It's a stupid rule anyway. It doesn't work in practice.
The real rule for memory management is not to use dynamic
allocation at all, except when the object lifetime is
explicit (e.g. a call in a telephone system). And of course
then, your design (or more directly, your requirements
specification) determines when the object should be deleted.
A new way I've been thinking about RAII is the following: All
"free resource calls", like delete, release mutex, close
connection, etc., should be made only inside destructors.
There are two major problems with this: it doesn't always apply,
and it only concerns resources. What you're concerned about is
program coherence: freeing a mutex lock (in a destructor) when
you've left the locked data in an inconsistent state, for
example, is not going to help. You must ensure that the
destructor also leaves the object in a coherent state. (This is
what is often meant by exception safety, but it really concerns
anything which might affect program flow.)
Specifically, all resources at all times should have a clearly
identified owner who frees the resource in its destructor, or
the resource is a stack object.
This is fine to a point, but I am supposing that the "identified
owner" is an object, and instance of a class. If that object is
dynamically allocated, and you're considering memory as a
resource, then you have a vicious circle.
It's easy to extend this idea to shared ownership. Optionally,
you can free resources early as long as the resource still has
an owner which would still free the resource if you
"accidentally" commented out the early release.
The idea is that maintaining the invariant of "ownership"
using destructors produces easier to follow code, and less
leaky code. RAII is all about ownership responsibilities. I
haven't taken enough time to look through all examples, so
please treat this as a tentative idea from myself. Obviously
there will be exceptions to this rule, I think.
The problem is that in many cases, the "owner" of an object is
the object itself. The whole basis of OO is that objects have
behavior; that behavior often determines their lifetime. (It's
not for nothing that most deletes in well written code are
"delete this", at least in some application domains.)