Repository navigation
Boost.Graph 1.93: pass stateful visitors with std::ref #700
Becheler
announced in
Announcements
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
Hi Boost.Graph community 😄
Starting with Boost 1.93, you can pass a visitor with
std::refto any BGL algorithm that takes one (listed under Supported algorithms below) 🚀Note
No action required for most users. This is an opt-in extension: existing code compiles and behaves exactly as before.
Warning
Unless you use planar algorithms.
planar_face_traversal,make_connected,make_biconnected_planarandmake_maximal_planartook the visitor by reference. 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 inboost::graph:See Deprecated interfaces below for the reasons and the migration.
Problem
BGL algorithms copy their visitor, so state stored in the visitor itself was lost. The recommended approach was to store references or pointers in the visitor, but a reference member:
constor references in a copyable or movable type")cppcoreguidelines-avoid-const-or-ref-data-members,which frustrated users.
Additionally, four planar graph algorithms deviated from the convention by taking visitors by reference (see Deprecated interfaces below).
Solution
Starting from 1.93, algorithms let callers opt into shared state explicitly with
std::ref, the idiom already used bystd::thread,std::bindandstd::make_tuple. The visitor can simply own its state.The Before and After examples below show the difference. For why we chose this approach see Design Rationale, and for how it works see Implementation Notes, both further down.
Before (Boost 1.92)
State had to live outside the visitor, behind a reference member. clang-tidy flags it with
cppcoreguidelines-avoid-const-or-ref-data-members. (The aggregate initialization below needs C++17.)After (Boost 1.93)
The visitor owns its state, and
std::refopts into sharing it with the algorithm. No warning.Supported algorithms
All available in Boost 1.93. Every algorithm below accepts both
visandstd::ref(vis), through every interface it provides (positional and, where one exists, named parameters).breadth_first_search,breadth_first_visitdepth_first_search,depth_first_visitmaximum_adjacency_searchneighbor_breadth_first_search,neighbor_breadth_first_visitundirected_dfs,undirected_depth_first_visitastar_search,astar_search_tree,astar_search_no_init,astar_search_no_init_treebellman_ford_shortest_pathsdag_shortest_pathsdijkstra_shortest_paths,dijkstra_shortest_paths_no_initdijkstra_shortest_paths_no_color_map,dijkstra_shortest_paths_no_color_map_no_initr_c_shortest_pathsprim_minimum_spanning_treedijkstra_shortest_paths)bron_kerbosch_all_cliqueshawick_circuits,hawick_unique_circuitstiernan_all_cyclesbiconnected_componentscore_numbers,weighted_core_numbersmetric_tsp_approx,metric_tsp_approx_from_vertexboost::graph, old ones deprecated, see next section)make_biconnected_planarmake_connectedmake_maximal_planarplanar_face_traversalDeprecated interfaces
Four planar algorithms took the visitor by non const reference:
planar_face_traversalmake_connectedmake_biconnected_planarmake_maximal_planarSwitching them to by value in place would have silently changed the behavior of existing code that relies on its visitor being updated. Adding by-value overloads next to them in
boost::was not possible either, since a call with a named visitor would be ambiguous between the two.So instead, for those 4 algorithms specifically:
std::ref) live in theboost::graphnamespace, e.g.,boost::graph::make_connected.boost::overloads, including those that take no visitor, are markedBOOST_DEPRECATED. They keep their existing behavior and share the implementation with the new ones. Their removal is planned for Boost 1.95, and the documentation says so. This is also consistent with our decision to progressively move algorithms to theboost::graphnamespace, see Deprecations Plans #675.boost::overloads and get the deprecation warning instead of a silent change.To migrate, call the
boost::graph::version, even if you pass no visitor, and wrap the visitor instd::refif you read its state after the call.Design Rationale
Most BGL algorithms take their visitors by value, following the STL convention for function objects. A visitor that accumulates state (a counter, a list of discovered vertices, a convergence flag) therefore updates a copy, and the caller sees nothing: the code compiles, runs, and is silently wrong.
The usual workarounds each had a cost:
planar_face_traversal(g, embedding, my_visitor{}), and the promise was fragile:make_maximal_planartook its visitor by reference yet copied it internally, so the caller's object was never updated.std::for_eachdoes. That steals the return type from algorithms that already return something meaningful, such asbellman_ford_shortest_pathsreturning abool.The chosen design keeps visitors by value and lets callers opt into shared state explicitly with
std::ref, the idiom already used bystd::thread,std::bindandstd::make_tuple. The mechanics are described in Implementation Notes below.Implementation Notes
How does BGL accept both
visandstd::ref(vis)?Counteror asstd::reference_wrapper<Counter>.At the entry point, each algorithm uses two small helpers from
boost/graph/detail/visitor_wrapper.hpp:unwrap_visitor_t<Visitor>gives the visitor type you wrote:CounterstaysCounter, andstd::reference_wrapper<Counter>becomesCounter. The compile-time check that the visitor provides the required event functions then runs on your type, not onstd::reference_wrapper, which has none of them.deref_visitor(vis)returns a reference to the visitor the algorithm should call: its own local copy for a plain visitor, or the caller's object (via.get()) for astd::reference_wrapper.The visitor is resolved once, and the internals receive that reference from then on:
A plain visitor behaves exactly as before: the algorithm owns its own copy and discards it at the end. With
std::ref, every event reaches the caller's object, and the call site makes the shared state and its lifetime visible.All reactions