Why all the PROTECT/UNPROTECT in rstan?

18 views
Skip to first unread message

Krzysztof Sakrejda

unread,
Jul 10, 2015, 2:42:35 PM7/10/15
to stan...@googlegroups.com
I'm looking at the rstan code and I keep seeing a pattern that doesn't make sense to me. The pattern is this:

SEXP __sexp_result;
PROTECT(__sexp_result = Rcpp::wrap(params_r));
UNPROTECT(1);
return __sexp_result;

With Rcpp I've always just been able to return objects to R by doing:

return Rcpp::wrap(params_r);

With a few exceptions this works for me (no segfaults/etc...). This is also what the Rcpp book and vignette recommend, from the vignette:

The RObject class takes advantage of the explicit life cycle of
C++ objects to manage ex-posure of the underlying R object to the garbage collector. The RObject effectively treats its underlying SEXP as a resource. The constructor of the RObject class takes the necessary measures to guarantee that the underlying SEXP is protected from the garbage collector, and
the destructor assumes the responsibility to withdraw that protection.
By assuming the entire responsibility of garbage collection,
Rcpp relieves the programmer from writing boiler plate code to manage the protection stack with PROTECT and UNPROTECT macros

I never got into programming with C/R before Rcpp came around so I'm not sure if there's some additional motivation here but it's confusing (me).

Krzysztof

Jiqiang Guo

unread,
Jul 10, 2015, 3:16:22 PM7/10/15
to stan...@googlegroups.com
I am just mimicking the code generated by source_cpp, which is like this at the moment I looked at it.

I didn't bother to understand why and I don't find it confusing.  It's at most redundant.


Jiqiang 
--
You received this message because you are subscribed to the Google Groups "stan development mailing list" group.
To unsubscribe from this group and stop receiving emails from it, send an email to stan-dev+u...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Krzysztof Sakrejda

unread,
Jul 10, 2015, 3:36:35 PM7/10/15
to stan...@googlegroups.com
On Friday, July 10, 2015 at 3:16:22 PM UTC-4, Jiqiang Guo wrote:
> I am just mimicking the code generated by source_cpp, which is like this at the moment I looked at it.
> I didn't bother to understand why and I don't find it confusing.  It's at most redundant.

Makes more sense now, thanks! I think source_cpp might just be very defensive since you otherwise could force it to assign/wrap/return in the same statement and that doesn't always work. Otherwise it's just doing PROTECT/UNPROTECT twice (once for the Rcpp object wrapper and once explicitly). If you have a wrap-able object in hand you can always do "return Rcpp::wrap(obj);".

Krzysztof
Reply all
Reply to author
Forward
0 new messages