- // loop over children
- Impl::BufferPositionMap::iterator it = d->children_positions.begin();
- Impl::BufferPositionMap::iterator end = d->children_positions.end();
- for (; it != end; ++it) {
- Buffer * child = const_cast<Buffer *>(it->first);
- if (d->cloned_buffer_)
- delete child;
- // The child buffer might have been closed already.
- else if (theBufferList().isLoaded(child))
- theBufferList().releaseChild(this, child);
- }
+ if (isClone()) {
+ // this is in case of recursive includes: we won't try to delete
+ // ourselves as a child.
+ d->clone_list_->erase(this);
+ // loop over children
+ Impl::BufferPositionMap::iterator it = d->children_positions.begin();
+ Impl::BufferPositionMap::iterator end = d->children_positions.end();
+ for (; it != end; ++it) {
+ Buffer * child = const_cast<Buffer *>(it->first);
+ if (d->clone_list_->erase(child))
+ delete child;
+ }
+ // if we're the master buffer, then we should get rid of the list
+ // of clones
+ if (!parent()) {
+ // if this is not empty, we have leaked something. worse, one of the
+ // children still has a reference to this list.
+ LASSERT(d->clone_list_->empty(), /* */);
+ list<CloneList *>::iterator it =
+ find(cloned_buffers.begin(), cloned_buffers.end(), d->clone_list_);
+ LASSERT(it != cloned_buffers.end(), /* */);
+ cloned_buffers.erase(it);
+ delete d->clone_list_;
+ }
+ // FIXME Do we really need to do this right before we delete d?
+ // clear references to children in macro tables
+ d->children_positions.clear();
+ d->position_to_children.clear();
+ } else {
+ // loop over children
+ Impl::BufferPositionMap::iterator it = d->children_positions.begin();
+ Impl::BufferPositionMap::iterator end = d->children_positions.end();
+ for (; it != end; ++it) {
+ Buffer * child = const_cast<Buffer *>(it->first);
+ if (theBufferList().isLoaded(child))
+ theBufferList().releaseChild(this, child);
+ }