> Using pointers (whether pointing to locals or globals) is always error
> prone. Think of deleting/overwriting the referenced object somewhere in
> the huge code base or think of subtly buggy pointer arithmetics; you
> won't notice. Same thing with malloc()/new: 

Unfortunately, C++ requires the use of pointers in at least two
situations:

1) Polymorphic classes. I.e. when you exploit inheritance, you have
   to use pointers or references to do polymorphic dispatching.
2) Recursive data structures. I.e. when you want to define a list,
   a tree, or a graph, there has to be a pointer somewhere.

Now, luckily, both of these cases can be encapsulated with a hosting
encapsulation class that manages the dynamic memory management. The key 
insight is that this encapsulating class should be default constructible, 
and optionally copy constructible, or even assignable in the STL sense.
When this is the case, you can treat the contents as POD, i.e. Plain
Old Data, and don't have to worry about dynamic memory and pointers.

The new menu code in LyX 1.1.x is an example of encapsulation a recursive
data structure (i.e. a monomorphic tree) in an encapsulation class. It's
quite simple to do this, once you get the idea. The first time, it's a bit
tricky, but after that, you will have no problem doing it.

The new kernel is an example of how to encapsulate both a polymorphic class
hierarchy and a recursive data structure in a hosting class, dupped the
Element.  Since I designed that, I have come up with a further simplification
such that the data structure itself will be build from Elements, rather than
pointers to elements.  This is not implemented in the new LyX kernel, but
at some point, I might do that.

Greets,

Asger

Reply via email to