Re: inheritance, list of objects, polymorphism
On Dec 16, 12:02 pm, Michael Doubez <michael.dou...@free.fr> wrote:
On 16 d=E9c, 09:53, James Kanze <james.ka...@gmail.com> wrote:
[...]
Yes, you stores Expression values. You should store Expression
pointers which raises the problem of deep copy. It is usually solved
by implementing a 'virtual Expression* clone ()' operation.
Another alternative is to use the Envelope/Letter idiom.
Which just hides the cloning.
And handles automatically the deletion in containers and some hard
cases of exception safety.
I also though the Envelope/Letter idiom would be a good choice for
symbolic calculus code because type promotion is handled seamlessly.
If you need to support promotion, yes. Envelope/Letter is the way to
go. (That is, after all, what Coplien invented it for.) But for just
simple expressions, where the objects represent nodes in the
expression
tree, it's probably overkill; just using pointers (shared_ptr if you
don't have anything better for memory management) is largely
sufficient,
and considerably easier to implement.
If Expression objects are immutable (and they probably should be),
then a much simpler solution would be to use reference semantics
(i.e. pointers) everywhere. Depending on the application, this
might even be a case where shared_ptr is appropriate---an expression
tree is just that, a tree, and can't have cycles. (There are other
solutions, with better performance, but they generally require more
work.)
Yes. Or something like boost's intrusive_ptr<>; AMA it wouldn't be too
onerous in development.
Or installing garbage collection. But installation of the Boehm
collector isn't always trivial. But what I was thinking of was some
sort of block allocator, where all of the nodes in a given expression
(and no other nodes) are allocated by a separate instance of the
allocator, and when finished with the entire expression, you simply
destruct the allocator, and that frees all of the memory it manages.
Without the need to walk the tree deleting the nodes one by one.
(Done
correctly, allocating a single node is just a comparison and a
subtraction -- an order of magnitude faster than more general
allocators --, and you never free an individual node.)
--
James Kanze