This implementation will not work with C++20 coroutines.<p>With coroutines, implementing dynamic scope becomes a lot more interesting, because switching to different coroutines requires switching which dynamic bindings are active.<p>The correct implementation is somewhat subtle and not immediately obvious if you haven't thought about it a lot. <a href="http://okmij.org/ftp/papers/DDBinding.pdf" rel="nofollow">http://okmij.org/ftp/papers/DDBinding.pdf</a> lays it out formally, but in the end the correct implementation is for each coroutine to have its own stack of dynamic bindings, and when you resume a coroutine in some context, you extend the bindings in that context with the coroutine's set of bindings while the coroutine is running, and remove those bindings again when the coroutine is done running. This preserves the intuitive behavior that one expects from dynamic scope - see the paper for more justification.<p>Others have got this wrong too, so you're in good company. Python, for example, added contextvars with <a href="https://www.python.org/dev/peps/pep-0567/" rel="nofollow">https://www.python.org/dev/peps/pep-0567/</a>, which have semantics which are <i>usually</i> identical to dynamic scope. But they chose an excessively-simple implementation, so the behavior diverges from proper dynamic scope when using coroutines in unusual ways, or using generators at all: <a href="https://www.python.org/dev/peps/pep-0568/" rel="nofollow">https://www.python.org/dev/peps/pep-0568/</a>