Traverse AST and save Stmt* pointers for later use

Hello everyone!

I am writing a tool that traverses ASTs of my project files, stores several Stmt* pointers, and then compares them as present here .

Currently I have a class that inherits ast_matchers::MatchFinder::MatchCallback and in its void run(const MatchResult &match) stores pointers of interest to a container. However it seems that at some point during/after the run() is finished, those pointers invalidate - e.g. if I check body->getStmtClass() during run, it correctly shows CompoundStmt , but afterwards it turns into some other clearly wrong class like If or For.

What are my options to solve this problem? I am aware that AST Matchers might be a wrong tool in this case, so please don't hesitate to advise other means if those will suit me better.

Best regards,
Igor Ivanov