[Cs3] stateful vistor and composite

Mikhail Nesterenko mikhail at cs.kent.edu
Mon Apr 20 15:36:57 EDT 2020


> 
> Page 336 of the Gamma text , regarding "(5) Accumulating State":
> would the stateful visitor object need to be treated as a functor so
> that memory deallocation of it's (lets say private) attributes is
> automatic when it leaves scope or would it need to be able to
> deallocate memory that may become allocated as it traverses some
> data structure and acclimates more objects of various derived
> classes manually.  As in: the visitor function iterates (or
> traverses) over some tree, and each node in that tree needs to
> modify the visitor so that the visitor maintains a record of
> pointers to the various visited derived class objects, and then
> create a copy of that object in persistent memory and add it to the
> end of the tree.  Think along the lines of procedural maze
> generation.  If that visitor function ends (reaching the end of the
> tree without adding a new node), would those objects be deallocated
> as it leaves the stack (unless allocated in the heap store) or would
> we have to (implicitly or explicitly) call the destructors for each
> traversed object to remove them somewhere else?  If they are
> persistent, could we just use another visitor function to deallocate
> specific nodes within a data structure, without having to deallocate
> the entire structure itself?  Does this make sense?

Well, a visitor is an object. It may very well keep a state after the
traversal. It is up to the programmer how it is to be deallocated. If
it is dynamically allocated, as is the case of ChildrenPrinter and
NamePrinter visitors in the genealogy.cpp example, then it should be
manually de-allocated. Something like:

  delete np; delete cp; 

In the example, the visitors are stateless so lack of de-allocation
does not cause a memory leak.

Another interesting question whether the visitor is changing the state
of the composite objects. Say, for example, every person in the
genealogical tree has age and the visitor "ages" every person by one
year.

That would be a nice exercise. I was meaning to set up a lab to do
something like that. Not this year though.

Thanks,
--
Mikhail


More information about the cs3 mailing list