In the last post where I described one issue related to usage of R’s data structures inside C++ code. The problem was caused by memory management system in R, which allows R to store two variables in the same place in the memory just after making an assignment.
See the following snippet:
#include <Rcpp.h> #include <vector> // [[Rcpp::plugins(cpp11)]] // [[Rcpp::export]] void change(Rcpp::NumericVector x) { // The C++ function does not return anything (it's void), // it only modifies the first element of the vector.
Connecting R with C++ is very easy because near all work needed to glue the code together is done by Rcpp. However, there are some very dangerous traps. C++, when used improperly can mess up a lot of things in the R session. In this post, I want to show you how to write secure C++ code to reduce the chances of breaking anything in R.
References. When working with R, we usually do not care if the object is copied or not.
In the last post, I wrote some notes about code optimization using Rcpp and C++. However, I forgot to add one main thought related to this topic:
“The First Rule of Program Optimization: Don’t do it. The Second Rule of Program Optimization (for experts only!): Don’t do it yet.”
I agree with that statement, and I made this mistake more than dozen times. I spent hours on optimizing the code, trying to get the results faster, and I most cases I succeed.