[Rcpp-devel] Unintentional modification of vector in place?

Dirk Eddelbuettel edd at debian.org
Mon Mar 20 19:13:53 CET 2017


Evan,

On 20 March 2017 at 12:02, Evan Cortens wrote:
| Thanks very much! Apologies for posting about something that has been covered
| elsewhere, I did search, but clearly not well enough. (Indeed, I see, this is
| almost exactly the same issue: https://stackoverflow.com/questions/11300048/
| rcpp-pass-by-reference-vs-by-value )

No worries. I think this should be in the R FAQ. I need to add something...

| On (3), apologies for being unclear, of course casting from int to double isn't
| an issue. I meant to say it could be an issue the other way around, namely,
| double to int. If you instead pass, for example, c(1.1, 2.2, 3.3, 4.4, 5.5,
| 6.6) to my example function, it'll silently cast that to an integer vector c(1,
| 2, 3, 4, 5, 6) (i.e., truncating). That said, this isn't really unexpected
| behaviour, rather exactly what you'd expect if you did {double x = 1.1; int y =
| (int) x;} in C. I'll pass on writing my own compiler, at least for now :)

I know. I was just being snarky -- some of these things we cannot test for as
the compiler gets in the way. As in should, because most of the time it does
know better.
 
| Finally, just to close the loop on this and to make sure I understand... if I
| don't want to modify the original vector, I should do this, yes?
| 
| cppFunction('IntegerVector test_int_vec(IntegerVector x) {
|   IntegerVector y = clone(x);
|   for ( R_xlen_t i = 0; i < x.size(); i++ )
|     y[i] = y[i] * 2;
|   return y;
| }')

Yes, pretty much.   And the simpler code here works too:

R> cppFunction("IntegerVector test_int_vec(IntegerVector x) { return 2*x; }")
R> vec <- c(1L, 2L, 3L)
R> test_int_vec(vec)
[1] 2 4 6
R> vec
[1] 1 2 3
R> 

Dirk

-- 
http://dirk.eddelbuettel.com | @eddelbuettel | edd at debian.org


More information about the Rcpp-devel mailing list