C++ Logo

STD-DISCUSSION

Advanced search

Subject: Re: std::variant - going from Alternative& to the enclosing variant&
From: Victor Khomenko (victor.khomenko_at_[hidden])
Date: 2020-08-26 05:49:28


> Instead of modifying the variant inside of the visitor, could you have the
> visitor return a signal that the variant should be modified?
>
> Another possibility would be to write a pure endomorphism
> from AST nodes to AST nodes. Instead of modifying the node, return a
> new one. Then at the top-level call site, assign the node to the newly returned one.

These two suggestions are plausible workarounds in some cases. However, they come at a price - e.g. the former one defers work that could be done inside the visitor back to the caller - and there can be many calling sites (e.g. a recursive visitor for AST with many node types). The latter is indeed a common technique in functional programming, but it means copying the whole AST even if a small local modification would be sufficient (or one would try re-using parts of the tree, but it's not easy if the visitor can modify the content of nodes, e.g. one would need to implement COW).

Anyway, this is not the point - I agree there are multiple workarounds for this problem, but this can be said about most features of the standard library. One should compare these workarounds with the proposed solution: The sheer convenience of going from an alternative to the enclosing variant at 0-cost is difficult to beat, and (imho) justifies the risk of UB (that can be mitigated as discussed in this thread).


STD-DISCUSSION list run by std-discussion-owner@lists.isocpp.org

Older Archives on Google Groups