[Rcpp-devel] Integer matrices in Rcpp and Armadillo

Dirk Eddelbuettel edd at debian.org
Sat Jun 8 22:19:07 CEST 2013


On 8 June 2013 at 12:48, Kevin Ushey wrote:
| I'm pretty the sure the Rcpp / RcppArmadillo way is to reuse memory whenever
| the types match between the as'ed containers, and copy if type coercion makes
| sense. Ie, an R integer vector --> an Rcpp IntegerVector would reuse the same
| memory, while an R integer vector --> an Rcpp NumericVector would require a
| copy and a coercion from integer to numeric. Similar things will apply between
| R and RcppArmadillo. Just remember that with R, numeric <-> double, integer <->
| signed int.
| 
| A simple example to illustrate (also shows how you can discover these things
| yourself):
| 
| ---
| 
| #include <Rcpp.h>
| 
| // [[Rcpp::export]]
| Rcpp::NumericVector test_numeric(Rcpp::NumericVector x) {
|   
|   x = x + 1;
|   return x;
|   
| }
| 
| // [[Rcpp::export]]
| Rcpp::IntegerVector test_integer(Rcpp::IntegerVector x) {
|   x = x + 1;
|   return x;
| }
| 
| /*** R
| x <- c(1, 2, 3)
| 
| test_numeric(x) ## returns c(2, 3, 4)
| print(x) ## x is now c(2, 3, 4)
| 
| test_integer(x) ## returns c(3, 4, 5)
| print(x) ## x is still c(2, 3, 4)
| */
| 
| ---

This is a known case and documented; I use something similar in every
(longer) talk about Rcpp when we motivate clone() as well. The long and short
of it is that a change in _type_ is equivalent to a copy and hence use of
clone(). 

| Since this thread has become rather long, I suggest generating your own minimal
| examples whenever you need to discover / be certain whether you're reusing
| memory or forcing a copy.

Yes, please. 

And editing out unused material from a repost is polite too.

Dirk

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


More information about the Rcpp-devel mailing list