[Rcpp-devel] Yet another design question regarding Rcpp

Romain Francois romain at r-enthusiasts.com
Wed May 5 09:20:56 CEST 2010

Le 04/05/10 22:26, Douglas Bates a écrit :
> In the files src/MatrixNs.{h,cpp} of the lme4a package (the
> development version of lme4, available only from R-forge) I create C++
> classes that parallel some of the S4 classes in the Matrix package for
> R.  Most of the time I apply operations in those classes to numeric
> vectors passed as arguments or components of arguments from R.  Thus
> many of the function signatures include arguments of the form
> NumericVector const&
> If I have a more complex operation to perform in C++ using temporary
> storage I could allocate the storage by declaring
>   NumericVector bar(foo.size());
> or something like that, even though this vector will never be touched
> by R.  I think this is the simplest approach so that I only need to
> use one set of function signatures in the MatrixNs.h declarations.
> Alternatively I could declared multiple function signatures for both
> NumericVector const&  and std::vector<double>  const&  arguments and
> allocate the temporary storage using std::vector<double>  instead of
> NumericVector.
> Or I could even declare all the function arguments as
> std::vector<double>  const&  and convert the NumericVector objects to
> that form (although I think that might involve some copying) before
> passing them.


> I am currently favoring using NumericVector to allocate the
> temporaries, even though the storage must be allocated and freed
> through R's mechanisms.
> Opinions?

It depends what you do with the data. If you change the size of the 
vector from time to time, add elements, remove elements, I'd go for 

For fixed size, I'd use R(cpp) data structures, which perform just as 
good as std::vector, both really are glorified C arrays. And then you 
have the option of returning the data to R cheaply.

One other way if you really wanted to use std::vector would be to wrap 
them in external pointers. but that's a bit more work.

Romain Francois
Professional R Enthusiast
+33(0) 6 28 91 30 30
|- http://bit.ly/9aKDM9 : embed images in Rd documents
|- http://tr.im/OIXN : raster images and RImageJ
|- http://tr.im/OcQe : Rcpp 0.7.7

More information about the Rcpp-devel mailing list