r/cpp • u/Foxi_Foxa • 14h ago
Boost.Graph 1.93: pass stateful visitors with std::ref
Dear Boost.Graph community,
Starting with Boost 1.93, you will be able to pass stateful visitors with std::ref :
Counter vis;
boost::depth_first_search(g, boost::visitor(std::ref(vis)));
// vis.count is now up to dateFor context, BGL visitors are small structures with event methods that are fired at specific points of an algorithm (e.g. the DFS algorithm calling vis.start_vertex(vertex, graph) at a certain point). Most visitors are meant to be pure observers and their events return void so they can't influence the execution flow of their algorithm. If a visitor only prints data, stateless is fine. But when wanting an answer out of a traversal (a yes/no, timestamps, paths...), it has to accumulate state.
Historically, algorithms implementation (circa 2000) predate std::ref (C++11). Any state stored in the visitor was therefore updated on a copy and lost. The recommended approach was to capture state through pointer or reference. But a reference member contradicts Core Guideline C.12 and triggers clang-tidy's cppcoreguidelines-avoid-const-or-ref-data-members, as reported by a redditor: https://www.reddit.com/r/cpp_questions/comments/1oj6mi6/boost_graph_library_example_seems_to_run_afoul_of/
From 1.93, algorithms will be able to unwrap visitors when the caller passed a reference_wrapper. It's an extension, you don't need to modify your existing code if it works. But if you want to silence the clang-tidy once for all, you now can 😄
Four exceptions to this: we had 4 planar algorithms that surprisingly took visitors by reference, against this convention, and needed to be deprecated to harmonize their signatures:
- planar_face_traversal,
- make_connected,
- make_biconnected_planar
- make_maximal_planar
In 1.93, your calls still compile and behave the same, but they now emit a deprecation warning, and the old overloads are planned for removal in Boost 1.95. The replacements live in boost::graph namespace (we are harmonizing namespaces progressively too)
boost::make_connected(g, vm, vis); // still works, deprecated
boost::graph::make_connected(g, vm, std::ref(vis)); // replacementAll details, explanations and rational live in the dedicated Github Discussion: https://github.com/boostorg/graph/discussions/700
See you there ! 🥳
4
u/obsidian_golem 13h ago
Why not make all the functions take a forwarding reference instead?