[Rcpp-devel] Rcpp vector classes vs std::vector for custom class member variables
Romain Francois
romain at r-enthusiasts.com
Tue Oct 8 14:25:27 CEST 2013
Le 08/10/13 13:04, Jon Clayden a écrit :
> Dear all,
>
> 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;
> }
>
> Are there garbage collection issues when these live inside an XPtr<Foo>?
No. An XPtr<Foo> will delete the object it points to, using Foo's
destructor when it goes out of scope.
I would argue against using external pointers directly when you can use
modules and experience more type safety than with direct external pointers.
But these (using external pointers and using modules) only make sense
when you want to be able to hold a reference to your object at the R
level, do you ?
> Are there speed advantages of std::vector<double> over
> Rcpp::NumericVector for general use? Any input would be welcome. Thanks
> in advance.
This is premature optimization. What you want to ask yourself is what
are you going to do with "bar". If bar goes back and forth between the
C++ and the R side, then NumericVector is your best candidate.
If bar is something internal to your class, then std::vector<> is fine
and will give you a more complete interface, will grow efficiently, etc ...
If you really want to have the best performing class for your
application, you need to measure it.
It is easy enough to make Foo a template and switch between the two in
benchmarking:
template <typename Container>
class Foo {
private:
Container bar ;
} ;
Foo< std::vector<double> > f1;
Foo< Rcpp::NumericVector > f2;
> 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...!
Great. You don't need expert knowledge of C++ for Rcpp to be useful.
--
Romain Francois
Professional R Enthusiast
+33(0) 6 28 91 30 30
More information about the Rcpp-devel
mailing list