[Rcpp-devel] Function changing the value of objects in global environment
Dirk Eddelbuettel
edd at debian.org
Sun Feb 2 02:34:37 CET 2014
Nick,
On 1 February 2014 at 20:14, Nick Menzies wrote:
| Hi all,
|
| I am relatively new to Rcpp and a bit confused about the behavior I am seeing
| from an Rcpp function. It seems that a function created with Rcpp can modify
| the value of objects in the global environment, yet this behavior depended on
| the nature of the object. I realize I could code things differently so that the
| object in the global environment is not affected, but I wanted to make sure
| there is not something more general I am doing wrong (and which will continue
| to be wrong without me knowing it!)
Yes. It is known and documented as has been discussed several times here.
In short in ...
| Below is a small example where the global value gets altered, followed by an
| example where it does not. The only difference between them is that in the
| first (cTest1) the input is NumericVector, while in the second (cTest2) the
| input is double.
|
| ### Rcpp function alters values in global environment:
| cppFunction('
| double cTest1( NumericVector zzz) {
... this case zzz is really the same as the R object, so the change has side
effects. We are after all passing a _pointer_ -- the P in SEXP object. If
you want to prevent this, use Rcpp::clone(...) on some object which creates a
distinct copy.
| zzz = zzz/10;
| return 1;
| }')
|
| zzz=rep(10,3)
| zzz
| cTest1(zzz)
| zzz
|
| ### Rcpp function does not alter values in global environment:
| cppFunction('
| double cTest2( double zzz) {
This is different as a double does not exists in R (it would be a vector of
length one, and correspond to a NumericVector as above -- a double really is
different). So here you have effect of Rcpp::clone() by an implicit copy.
Idem when a cast is involved.
Hope this helps, Dirk
| zzz = zzz/10;
| return 1;
| }')
|
| zzz=10
| cTest2(zzz)
| zzz
| ####################
|
|
| Thanks for your help, and sorry for the naive question.
|
| Nick
|
| PS - I am running Rcpp 0.10.6, R version 3.0.1
|
| ----------------------------------------------------------------------
| _______________________________________________
| Rcpp-devel mailing list
| Rcpp-devel at lists.r-forge.r-project.org
| https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel
--
Dirk Eddelbuettel | edd at debian.org | http://dirk.eddelbuettel.com
More information about the Rcpp-devel
mailing list