From khansen at stat.Berkeley.EDU  Tue May 23 08:39:31 2006
From: khansen at stat.Berkeley.EDU (Kasper Daniel Hansen)
Date: Mon, 22 May 2006 23:39:31 -0700
Subject: [Rd] protect
Message-ID: <35168A7B-DFA1-42F7-8763-7769B449005B@stat.berkeley.edu>

I have a few simple questions about the usage of PROTECT, more  
specifically how careful one needs to be. Simple yes/no answers are  
fine.

Most of the uses I have seen do protection when memory is allocated.  
But what if one just want to assign a value of another function to a  
variable. Say eg. that foo is a function that returns a SEXP. Would  
the following code be fine?

SEXP bar;
PROTECT(bar = foo());

Also, basically in one use case I would want to return the value of  
foo immediately, but I need to do some cleaning up first, which has  
nothing to do with R (more specifically, I need to close various  
files). Would I then need to protect foo, as in

SEXP bar;
bar = foo();
"close the file in C++"
return bar;

Finally, I am also assigning values to the components of a list.  
Would the following be ok

SEXP bar;
PROTECT(bar = NEW_LIST(2));
SET_VECTOR_ELT(bar, 0, ScalarInteger(test());

(where test is a function returning int, which again has nothing to  
do with R - it interfaces to an extern library), or do I need to  
hedge myself against garbage collection in the SET_VECTOR_ELT macro?

/Kasper



[Rd] protect
Kasper Daniel Hansen