r-lib / cpp11

cpp11 helps you to interact with R objects using C++ code.
https://cpp11.r-lib.org/
Other
201 stars 48 forks source link

Fix RNG code example in `converting.Rmd` #159

Closed klmr closed 3 years ago

klmr commented 3 years ago

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.

jimhester commented 3 years ago

You are correct, thanks for the pull request!