[Rcpp-devel] Rcpp vector classes vs std::vector for custom class member variables

Dirk Eddelbuettel edd at debian.org
Tue Oct 8 13:34:35 CEST 2013


Hi Jon,

On 8 October 2013 at 12:04, Jon Clayden wrote:
| I'm new to Rcpp and this mailing list. I did look for a previous answer to this
| question, but it's hard to summarise succinctly so I may have missed something.
| Apologies if so.
| 
| I'm defining a custom class, an object of which will need to survive across
| various calls back and forth between R and C++, so I plan to use the XPtr class
| to wrap a pointer. My question is, what are the advantages and disadvantages of
| using Rcpp vector classes (vs std::vector) for member variables? To be more
| concrete, I mean
| 
| class Foo
| {
| private:
|   Rcpp::NumericVector bar;
| }
| 
| vs
| 
| class Foo
| {
| private;
|   std::vector<double> bar;
| }

Here is the first choice: std::vector<double> vs Rcpp::NumericVector.  

Generally speaking I would use the former when I know I will interface other
C++ code requiring that interface.  I use the latter if I need to 'just' pass
things back and forth and maybe use my own (locally added) routines. [ And
you can go pretty cheaply from Rcpp::NumericVector to std::vector. ]

I use a third (arma::vec and its matrices) when I do linear algebra. (And
could also use RcppEigen for different vectors).
 
| Are there garbage collection issues when these live inside an XPtr<Foo>?

XPtr means R does not touch it. There will never be a gc.  So XPtr makes less
sense with R classes -- you want to be 'away from R' already for (large)
objects so I would tend to use XPtr of std::vector.  Or maybe even XPtr of
your class Foo.  Or use Jay and Mike's bigmemory (which uses an external
pointer internally too). It all depends.

| Are there speed advantages of std::vector<double> over Rcpp::NumericVector
| for general use? Any input would be welcome. Thanks in advance.

I would profile rather than believing what random stranger on the Internet
tell you :)  But ex ante there should not be a large difference.  Returning
from std::vector to R may involve a copy -- not sure. 
 
| Great work on Rcpp, by the way. I've been hearing very good things for quite
| some time, but wasn't sure if it was worth dusting off my slightly rusty C++
| for. Suffice to say I think it was. The API is very clean and returning to the
| standard R API will be painful...!

Thanks! Glad you are finding it useful.

Dirk

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


More information about the Rcpp-devel mailing list