> >> SEXP mkans(double x) > >> { > >> SEXP ans; > >> ans = PROTECT(allocVector(REALSXP, 1)); > >> REAL(ans)[0] = x; > >> UNPROTECT(1); > >> return ans; > >> }
> >One should also note that the PROTECT within mkans is unnecessary, > >and must surely be confusing to anyone who thought (correctly) > >that they had understood what PROTECT is for. > > I understand what PROTECT is for and I don't find the PROTECT in mkans > confusing. > > Maybe it's not necessary now. But it's so much simpler/safer to just > systematically protect any freshly allocated SEXP. One day > someone might need to modify mkans(), say, add a call to warning() or > Rprintf() after the call to allocVector(), and will most likely forget > to add the PROTECT/UNPROTECT that will then become necessary. There's certainly something to be said in favour of the "better safe than sorry" approach to using PROTECT. But in the context of a tutorial, one shouldn't put one in that's unnecessary without a comment saying, "not needed at the moment, but would be if code that allocates more memory is added later, so let's be safe and do it now too". Otherwise, the reader may infer an incorrect model of when to PROTECT, such as "you should PROTECT every allocated object, then UNPROTECT at the end of the procedure - do that and you'll be OK". Of course, that's not enough to be OK. And to illustrate the correct model, one needs some negative examples as well as positive examples. Radford Neal ______________________________________________ R-devel@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-devel