The code example that intends to save the R RNG state was broken: local_rng(); creates a temporary object that ceases existing at the end of the full expression, i.e. before the rest of the body of the function foo is executed. To prevent this, the object must be named.
Additionally, depending on the compiler settings, the above might cause an “unused object” warning (though GCC 10 doesn’t even with -Wunused-variable, because this usage pattern is recognised).
A common solution is to wrap the scope guard usage into a macro:
#define PASTE1(x, y) x ## y
#define PASTE(x, y) PASTE1(x, y)
#define RNG_GUARD auto PASTE(_rng, __LINE__) = local_rng(); (void) PASTE(_rng, __LINE__)
…
void foo() {
RNG_GUARD;
}
… or one could use a wrapper similar to unwind_protect.
The code example that intends to save the R RNG state was broken:
local_rng();
creates a temporary object that ceases existing at the end of the full expression, i.e. before the rest of the body of the functionfoo
is executed. To prevent this, the object must be named.Additionally, depending on the compiler settings, the above might cause an “unused object” warning (though GCC 10 doesn’t even with
-Wunused-variable
, because this usage pattern is recognised).A common solution is to wrap the scope guard usage into a macro:
… or one could use a wrapper similar to
unwind_protect
.