what can I do to make sure that local variables are left in place?
Either use (named) local variables, not temporaries; or modify addVisitor
to store a copy of the visitor rather than a reference to it, if that's feasible.
Would assigning visitors to local variables be enough to ensure they won't be reused?
Yes.
Does standard provides any promise on the stack variables after their last use in function code?
Temporaries (unnamed objects created during an expression, such as the visitors you create) live until the end of the full-expression that creates them. So they last until the call to addVisitor
returns, but are destroyed before the next line.
Local variables (automatic variables declared within a block of code) last until the program leaves the innermost block in which they are declared. When that happens, each local variable from that block is destroyed in the reverse order of their declarations. So in the following:
{
Visitor1 visitor1;
Visitor2 visitor2;
TreeWalker walker;
walker.addVisitor(nodeType1, visitor1);
walker.addVisitor(nodeType2, visitor2);
//...
walker.walkTree(tree);
}
it's guaranteed that walker
will be destroyed before the visitors, so it will not contain any dangling references even in its destructor.