Consider these 2 functions:
library(Rcpp)
cppFunction("NumericVector func1(NumericVector &x)
{
for (int i = 0; i < x.length(); i++)
x[i] = x[i] * 2;
return x;
}")
cppFunction("NumericVector func2(NumericVector x) // no &
{
for (int i = 0; i < x.length(); i++)
x[i] = x[i] * 2;
return x;
}")
The only difference is that func1
takes x
as a reference parameter, whereas func2
takes it as a value. If this was regular C++, I'd understand this as func1
being allowed to change the value of x
in the calling code, whereas this won't happen in func2
.
However:
> x <- 1:10/5 # ensure x is numeric, not integer
> x
[1] 0.2 0.4 0.6 0.8 1.0 1.2 1.4 1.6 1.8 2.0
> func1(x)
[1] 0.4 0.8 1.2 1.6 2.0 2.4 2.8 3.2 3.6 4.0
> x
[1] 0.4 0.8 1.2 1.6 2.0 2.4 2.8 3.2 3.6 4.0 # x in calling env has been modified
> x <- 1:10/5 # reset x
> x
[1] 0.2 0.4 0.6 0.8 1.0 1.2 1.4 1.6 1.8 2.0
> func2(x)
[1] 0.4 0.8 1.2 1.6 2.0 2.4 2.8 3.2 3.6 4.0
> x
[1] 0.4 0.8 1.2 1.6 2.0 2.4 2.8 3.2 3.6 4.0 # x is also modified
So it looks like func1
and func2
behave the same way, as far as side-effects on the arguments are concerned.
What is the reason for this? In general, is it better to pass arguments to Rcpp functions by reference or by value?