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

Dirk Eddelbuettel edd at debian.org
Tue Oct 8 15:19:55 CEST 2013

On 8 October 2013 at 13:53, Jon Clayden wrote:
| Sure. And the memory allocated to "bar" (if it's a NumericVector) will be
| protected from the garbage collector until the Foo object is deleted?

Yes, R objects created by Rcpp, eg Rcpp::NumericVector and all the other
Rcpp::* objects mapping to standard R types, are indistinguishable from
native R objects and behave the same at the R level as objects created by R.

That is essentially the whole point.

| I think I do... ;)  I need the object to hold state and not be deallocated
| between calls into the C++ code. I also want to allow for the possibility that
| multiple Foo objects exist, and are being operated on simultaneously. So
| holding a handle on the R side and passing it back to each C++ function that
| works with the object seems like the natural approach to me.

A really simple way to do that is that create a container class that has this
type as an object, and to create an init function, an accessor function, ...

Rcpp modules can do that for you too just via declarations, resulting in 
Reference Class objects at the R level.  This is a little more advanced;
maybe more suitable for your next project, or now if you are willing to read
up (Rcpp modules vignette, corresponding chapter in the Rcpp book, existing
packages, ...)

| Agreed, but it's a consideration. I fully accept that the choice depends on the
| particular application, as you and Dirk both said. I was just wondering what
| the baseline performance difference (if any) might be.

Nobody knows ex ante. There is no explicit slowdown baked in. As we have
suggested several times, you need to measure it!  

| Sure, but I'm doing quite a bit in native code so there's little point in
| dropping competent C code for badly-written C++. Yes, I could mix them, but
| it's nice to be able to make the most of the tools available... :)

You can do whatever you want and how you want to do it. You can write as much
K&R C code as you like.

Rcpp is here to get your data more seamlessly from R to C++ and back again,
and a lot else.  

If you then prefer to cast back to C, go for it. Not my style, but heck,
choice is good. It even lets people do silly things like work in C ;-)


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

More information about the Rcpp-devel mailing list